﻿using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.FP;
using Coldairarrow.Entity.ListSelection;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.Print;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_DesignListBusiness : BaseBusiness<PB_DesignList>, IPB_DesignListBusiness, ITransientDependency
    {
        readonly IOperator _operator;

        public PB_DesignListBusiness(IDbAccessor db, IPB_DesignDetailBusiness pbddb, IPB_MaterialBusiness pBMaterialBusiness, IOperator @operator)
            : base(db)
        {
            _pbddb = pbddb;
            _operator = @operator;
            _pBMaterialBusiness = pBMaterialBusiness;
        }

        IPB_DesignDetailBusiness _pbddb { get; }
        IPB_MaterialBusiness _pBMaterialBusiness { get; }

        #region 外部接口

        public async Task<PageResult<PB_DesignListBulidingDTO>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            //var q = GetIQueryable();
            var where = LinqHelper.True<PB_DesignListBulidingDTO>();
            var search = input.Search;


            Expression<Func<PB_DesignList, PB_Buildingnumber, PB_DesignListBulidingDTO>> select = (e, f) => new PB_DesignListBulidingDTO
            {

                BuildingnumberName = f.Buildingnumber  //楼号
            };
            select = select.BuildExtendSelectExpre();
            var q = from e in GetIQueryable().AsExpandable()
                    join f in Db.GetIQueryable<PB_Buildingnumber>() on e.BuildingNumberID equals f.Id into ef
                    from f in ef.DefaultIfEmpty()
                    select @select.Invoke(e, f);
            where = where.And(p => p.ExamineStatus == 2);
            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_DesignListBulidingDTO, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }
            //where = where.And(d => _operator.Property.DeptIds.Contains(d.DeptId));
            return await q.Where(where).GetPageResultAsync(input);
        }
        /// <summary>
        /// 朱柏清 2022-03-03 发货通知单中选择楼号
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public async Task<List<BuildingnumberDTO>> GetBuildingnumberDataListAsync(string projectId)
        {
            //string sqlstr = "select a.Id as BuildingNumberID,a.Buildingnumber as BuildingnumberName,b.Id from  PB_Buildingnumber a join PB_DesignList b on a.id=b.BuildingNumberID WHERE b.id  not in(SELECT DesignId from  PB_DeliveryNoticeItem a INNER JOIN PB_DeliveryNotice b on a.ParentId = b.id WHERE a.Deleted = 0 and b.Deleted = 0 and b.ProjectId = '" + projectId + "') and a.ProjectId = '" + projectId + "' and b.ExamineStatus=2 ; ";
            string sqlstr = @"select a.Id as BuildingNumberID,a.Buildingnumber as BuildingnumberName,b.Id,b.Type,c.`Name`,CONCAT(a.Buildingnumber,'/',c.`Name`) as BuiName from  PB_Buildingnumber a join PB_DesignList b on a.id=b.BuildingNumberID join PB_DesignListType as c on b.Type=c.Id WHERE b.id  not in(SELECT DesignId from  PB_DeliveryNoticeItem a INNER JOIN PB_DeliveryNotice b on a.ParentId = b.id WHERE a.Deleted = 0 and b.Deleted = 0 and b.ProjectId = '" + projectId + "') and a.ProjectId = '" + projectId + "' and b.ExamineStatus=2 ";
            var listdata = await Db.GetListBySqlAsync<BuildingnumberDTO>(sqlstr);
            return listdata;
        }
        /// <summary>
        /// 清单审核
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<PB_DesignList>> GetDataListToExamineAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_DesignList>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_DesignList, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }
            q = q.Where(x => x.ExamineStatus == 1);
            where = where.And(m => _operator.Property.DeptIds.Contains(m.DeptId));
            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PB_DesignList> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }
        public IQueryable<T> GetQueryableOK<T>() where T : class, new()
        {
            return Db.GetIQueryable<T>();
        }
        public async Task AddDataAsync(PB_DesignList data)
        {
            PB_DesignListVersion pbdata = new PB_DesignListVersion
            {
                Id = IdHelper.GetId(),
                ParentId = data.Id,
                VersionNumber = 1,
                CreatorId = _operator.UserId,
                CreatorRealName = _operator?.Property?.RealName,
                CreateTime = DateTime.Now,
                Deleted = false
            };
            await Db.InsertAsync(pbdata);
            data.IsPrint = false;
            await InsertAsync(data);
            //2022-03-04 朱柏清 项目执行过程明细
            PB_DesignList pB_DesignList = Db.GetIQueryable<PB_DesignList>().Where(s => s.Id == data.Id).FirstOrDefault();
            PB_ProjectProcess pB_ProjectProcess = new PB_ProjectProcess
            {
                Id = IdHelper.GetId(),
                ProjectId = pB_DesignList.ProjectId,
                ProjectName = pB_DesignList.ProjectName,
                ProcessType = Db.GetIQueryable<Base_EnumItem>().Where(u => u.EnumCode.Contains("ProjectProcessType") && u.Name.Contains("设计清单")).FirstOrDefault().Value,
                BuildingnumberId = pB_DesignList.BuildingNumberID,
                BuildingnumberName = Db.GetIQueryable<PB_Buildingnumber>().Where(u => u.Id == pB_DesignList.BuildingNumberID).FirstOrDefault().Buildingnumber,
                Remarks = "新增",
                CreatorId = _operator.UserId,
                CreatorRealName = _operator.Property.RealName,
                CreateTime = DateTime.Now,
                OrderId = pB_DesignList.Id,
                Deleted = false,
            };
            await Db.InsertAsync<PB_ProjectProcess>(pB_ProjectProcess);

        }

        public async Task UpdateDataAsync(PB_DesignList data)
        {
            await UpdateAsync(data);
        }
        public async Task<AjaxResult> DeleteDataAsync(List<string> ids)
        {
            AjaxResult res = new AjaxResult
            {
                Success = true,
                Msg = "请求成功！"
            };
            AjaxResult resReturn = new AjaxResult
            {
                Success = false,
                Msg = "已经做了单据!不可删除"
            };
            //根数据
            var atAllData = Db.GetListBySqlAsync<PB_DeliveryNoticeItem>("SELECT  *  FROM PB_DeliveryNoticeItem WHERE DesignId in (" + String.Join(", ", ids).Replace("\"", "'") + ") ").Result;
            if (atAllData.Count > 0)
            {
                return resReturn;
            }
            //2022-03-04 朱柏清 项目执行过程明细
            List<PB_ProjectProcess> pB_ProjectProcesseslist = new List<PB_ProjectProcess>();
            foreach (var item in ids)
            {
                PB_DesignList pB_DesignList = Db.GetIQueryable<PB_DesignList>().Where(s => s.Id == item).FirstOrDefault();
                PB_ProjectProcess pB_ProjectProcess = new PB_ProjectProcess
                {
                    Id = IdHelper.GetId(),
                    ProjectId = pB_DesignList.ProjectId,
                    ProjectName = pB_DesignList.ProjectName,
                    ProcessType = Db.GetIQueryable<Base_EnumItem>().Where(u => u.EnumCode.Contains("ProjectProcessType") && u.Name.Contains("设计清单")).FirstOrDefault().Value,
                    BuildingnumberId = pB_DesignList.BuildingNumberID,
                    BuildingnumberName = Db.GetIQueryable<PB_Buildingnumber>().Where(u => u.Id == pB_DesignList.BuildingNumberID).FirstOrDefault().IsNullOrEmpty()?"": Db.GetIQueryable<PB_Buildingnumber>().Where(u => u.Id == pB_DesignList.BuildingNumberID).FirstOrDefault().Buildingnumber,
                    Remarks = "删除",
                    CreatorId = _operator.UserId,
                    CreatorRealName = _operator.Property.RealName,
                    CreateTime = DateTime.Now,
                    OrderId = item,
                    Deleted = false,
                };
                pB_ProjectProcesseslist.Add(pB_ProjectProcess);
            }
            await Db.InsertAsync<PB_ProjectProcess>(pB_ProjectProcesseslist);
            string strid = "";
            foreach (var item in ids)
            {
                strid += "'" + item + "',";
            }
            strid = strid.Substring(0, strid.Length - 1);
            await ExecuteSqlAsync("delete from PB_DesignDetail where ParentId in (" + strid + ")");
            await ExecuteSqlAsync("delete from PB_DesignListVersion where ParentId in (" + strid + ")");
            await DeleteAsync(ids);


            return res;
        }
        public IQueryable<T> GetQueryable<T>() where T : class, new()
        {
            return Db.GetIQueryable<T>();
        }

        public async Task<List<DataTypeInfo>> GetDataLisJson(string id)
        {
            List<DataTypeInfo> dataTypeInfos = new List<DataTypeInfo>();
            var q = GetTypeAsyncs(id).Result;
            List<PB_MaterialDTO> list = await _pBMaterialBusiness.QueryDataQueryAsync(string.Join(",", q.Select(n => n.MaterialID).ToArray()), id);
            DataTypeInfo dataTypeInfo = new DataTypeInfo();
            dataTypeInfo.Data = q.FirstOrDefault();
            dataTypeInfo.Sub = list?.ToList();
            dataTypeInfos.Add(dataTypeInfo);
            return dataTypeInfos;
        }

        /// <summary>
        /// 获取设计清单信息
        /// </summary>
        /// <param name="id">设计清单Id</param>
        /// <param name="deatiltype">1设计清单明细；2、设计清单明细汇总</param>
        /// 接口调整增加项目名称和楼号   2022-02-21   赵锦涛
        /// <returns></returns>
        public async Task<DesignListDataDTO> GetDesignListDataAsync(string id, int deatiltype)
        {
            //PB_DesignList data = await Db.GetIQueryable<PB_DesignList>().Where(x => x.Id == id).FirstOrDefaultAsync();
            Expression<Func<PB_DesignList, PB_Project, PB_Buildingnumber, DesignDataDTO>> select = (a, b, c) => new DesignDataDTO
            {
                ProjectnameInfo = b.Name, //项目名称
                BuildingnumberName = c.Buildingnumber  //楼号
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_DesignList>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Project>() on a.ProjectId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Buildingnumber>() on a.BuildingNumberID equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            var data = await q.Where(x => x.Id == id).FirstOrDefaultAsync();

            // string sqlMain = @"select Id,`Code`,`Name`,Weight,UnitGroupName,State,Slot,VersionNumber,SUM(Nums) as Nums,SUM(RealNums) as RealNums from ( select a.MaterialId as Id,b.`Code`,b.`Name`,b.Weight,c.`Name` as UnitGroupName,a.Nums,a.Slot,a.RealNums,a.State,a.VersionNumber from PB_DesignDetail as a join PB_Material as b on a.MaterialId=b.Id join Base_UnitItems as c on b.storageId=c.Id where a.ParentId='" + id + "' and a.State=0 ) as t group by Id,`Code`,`Name`,Weight,UnitGroupName,State,VersionNumber,Slot  ORDER BY a.Slot";
            string sqlMain = string.Empty;
            if (deatiltype == 1)
            {
                //朱柏清 2022-03-02  
                sqlMain = @"SELECT 	Id,	`Code`,	`Name`,	Weight,	UnitGroupName,State,Slot,	Nums,	RealNums, 	SubId,IsStandard,	Remarks,IFNULL(Spec,'') Spec, case when ExamineStatus=4 then 1 else 0 end OriginalDetails,OneStep,TwoStep,ThreeStep,FourStep,FiveStep,SixStep,SevenStep,EightStep,NineStep,TenStep,ElevenStep,TwelveStep,ThirteenStep,FourteenStep,FifteenStep FROM	(	SELECT a.MaterialId AS Id,	b.`Code`,	b.`Name`,  a.Remarks ,	b.Weight,	c.`Name` AS UnitGroupName,	a.Nums,	a.Slot,	a.RealNums,	b.Spec,	a.State,	a.Id as SubId,b.IsStandard,d.ExamineStatus,a.OneStep,a.TwoStep,a.ThreeStep,a.FourStep,a.FiveStep,a.SixStep,a.SevenStep,a.EightStep,a.NineStep,a.TenStep,a.ElevenStep,a.TwelveStep,a.ThirteenStep,a.FourteenStep,a.FifteenStep	FROM	PB_DesignDetail AS a	JOIN PB_Material AS b ON a.MaterialId = b.Id	JOIN Base_UnitItems AS c ON b.storageId = c.Id join PB_DesignList as d on a.ParentId=d.Id 	WHERE	a.ParentId = '" + id + "'  ) AS t ORDER BY	a.SubId";
            } 
            //补加
            else if (deatiltype==3) {
                sqlMain = @"SELECT 	Id,	`Code`,	`Name`,	Weight,	UnitGroupName,State,Slot,	Nums,	RealNums, 	SubId,IsStandard,	Remarks,IFNULL(Spec,'') Spec, case when ExamineStatus=4 then 1 else 0 end OriginalDetails,OneStep,TwoStep,ThreeStep,FourStep,FiveStep,SixStep,SevenStep,EightStep,NineStep,TenStep,ElevenStep,TwelveStep,ThirteenStep,FourteenStep,FifteenStep FROM	(	SELECT a.MaterialId AS Id,	b.`Code`,	b.`Name`,  a.Remarks ,	b.Weight,	c.`Name` AS UnitGroupName,	a.Nums,	a.Slot,	a.RealNums,	b.Spec,	a.State,	a.Id as SubId,b.IsStandard,d.ExamineStatus,a.OneStep,a.TwoStep,a.ThreeStep,a.FourStep,a.FiveStep,a.SixStep,a.SevenStep,a.EightStep,a.NineStep,a.TenStep,a.ElevenStep,a.TwelveStep,a.ThirteenStep,a.FourteenStep,a.FifteenStep	FROM	PB_DesignDetail AS a	JOIN PB_Material AS b ON a.MaterialId = b.Id	JOIN Base_UnitItems AS c ON b.storageId = c.Id join PB_DesignList as d on a.ParentId=d.Id 	WHERE	a.ParentId = '" + id + "'  and a.State=1  ) AS t ORDER BY	a.SubId";
            }
            //减少
            else if (deatiltype == 4)
            {
                sqlMain = @"SELECT 	Id,	`Code`,	`Name`,	Weight,	UnitGroupName,State,Slot,	Nums,	RealNums, 	SubId,IsStandard,	Remarks,IFNULL(Spec,'') Spec, case when ExamineStatus=4 then 1 else 0 end OriginalDetails,OneStep,TwoStep,ThreeStep,FourStep,FiveStep,SixStep,SevenStep,EightStep,NineStep,TenStep,ElevenStep,TwelveStep,ThirteenStep,FourteenStep,FifteenStep FROM	(	SELECT a.MaterialId AS Id,	b.`Code`,	b.`Name`,  a.Remarks ,	b.Weight,	c.`Name` AS UnitGroupName,	a.Nums,	a.Slot,	a.RealNums,	b.Spec,	a.State,	a.Id as SubId,b.IsStandard,d.ExamineStatus,a.OneStep,a.TwoStep,a.ThreeStep,a.FourStep,a.FiveStep,a.SixStep,a.SevenStep,a.EightStep,a.NineStep,a.TenStep,a.ElevenStep,a.TwelveStep,a.ThirteenStep,a.FourteenStep,a.FifteenStep	FROM	PB_DesignDetail AS a	JOIN PB_Material AS b ON a.MaterialId = b.Id	JOIN Base_UnitItems AS c ON b.storageId = c.Id join PB_DesignList as d on a.ParentId=d.Id 	WHERE	a.ParentId = '" + id + "'  and a.State=2  ) AS t ORDER BY	a.SubId";
            }
            else if (deatiltype == 5)
            {
                sqlMain = @"SELECT 	Id,	`Code`,	`Name`,	Weight,	UnitGroupName,State,Slot,	Nums,	RealNums, 	SubId,IsStandard,	Remarks,IFNULL(Spec,'') Spec, case when ExamineStatus=4 then 1 else 0 end OriginalDetails,OneStep,TwoStep,ThreeStep,FourStep,FiveStep,SixStep,SevenStep,EightStep,NineStep,TenStep,ElevenStep,TwelveStep,ThirteenStep,FourteenStep,FifteenStep FROM	(	SELECT a.MaterialId AS Id,	b.`Code`,	b.`Name`,  a.Remarks ,	b.Weight,	c.`Name` AS UnitGroupName,	a.Nums,	a.Slot,	a.RealNums,	b.Spec,	a.State,	a.Id as SubId,b.IsStandard,d.ExamineStatus,a.OneStep,a.TwoStep,a.ThreeStep,a.FourStep,a.FiveStep,a.SixStep,a.SevenStep,a.EightStep,a.NineStep,a.TenStep,a.ElevenStep,a.TwelveStep,a.ThirteenStep,a.FourteenStep,a.FifteenStep	FROM	PB_DesignDetail AS a	JOIN PB_Material AS b ON a.MaterialId = b.Id	JOIN Base_UnitItems AS c ON b.storageId = c.Id join PB_DesignList as d on a.ParentId=d.Id 	WHERE	a.ParentId = '" + id + "'  and a.State=0  ) AS t ORDER BY	a.SubId";
            }
            else
            {
                sqlMain = @"SELECT Id, `Code`, `Name`,Weight,	UnitGroupName,SUM( Nums ) AS Nums,SUM( RealNums ) AS RealNums ,IsStandard,IFNULL(Spec,'') Spec FROM(SELECT
		a.MaterialId AS Id,b.`Code`,b.`Name`,b.Weight,c.`Name` AS UnitGroupName,a.Nums,a.Slot,a.RealNums,a.State,a.Id AS SubId,b.IsStandard,b.Spec	FROM		PB_DesignDetail AS a JOIN PB_Material AS b ON a.MaterialId = b.Id JOIN Base_UnitItems AS c ON b.storageId = c.Id WHERE a.ParentId = '" + id + "' 		AND a.State = 0 UNION ALL	SELECT a.MaterialId AS Id,b.`Code`,	b.`Name`,b.Weight,c.`Name` AS UnitGroupName,	a.Nums,a.Slot,a.RealNums,	a.State,	a.Id AS SubId,	b.IsStandard,b.Spec FROM PB_DesignDetail AS a JOIN PB_Material AS b ON a.MaterialId = b.Id JOIN Base_UnitItems AS c ON b.storageId = c.Id 	WHERE	a.ParentId = '" + id + "' 	AND a.State = 1 UNION ALL	SELECT		a.MaterialId AS Id,	b.`Code`,b.`Name`,	b.Weight,		c.`Name` AS UnitGroupName,		(- a.Nums ) AS Nums,a.Slot,(- a.RealNums ) AS RealNums,a.State,a.Id AS SubId,b.IsStandard,b.Spec FROM PB_DesignDetail AS a JOIN PB_Material AS b ON a.MaterialId = b.Id	JOIN Base_UnitItems AS c ON b.storageId = c.Id 	WHERE	a.ParentId = '" + id + "' 	AND a.State = 2 ) AS t GROUP BY Id,`Code`,`Name`,Weight,UnitGroupName,IsStandard,Spec";

            }
            var listdata = await Db.GetListBySqlAsync<PB_DesignDetailListDataDTO>(sqlMain);
            DesignListDataDTO dataTypeInfo = new DesignListDataDTO();
            dataTypeInfo.Data = data;
            dataTypeInfo.Sub = listdata;
            return dataTypeInfo;
        }


        public async Task<List<DataTypeDTO>> GetTypeAsyncs(string ParentId)
        {
            Expression<Func<PB_DesignList, PB_DesignDetail, PB_Material, PB_MaterialType, PB_Project, PB_Buildingnumber, DataTypeDTO>> select = (e, a, b, c, d, f) => new DataTypeDTO
            {
                MaterialID = a.MaterialId,//物料编号
                MaterialName = b.Name,//物料名称
                MaterialTypeId = c.Name,//类型名称
                MaterialCode = b.Code,//物料编号
                ProjectnameInfo = d.Name, //项目名称
                BuildingnumberName = f.Buildingnumber  //楼号
            };
            select = select.BuildExtendSelectExpre();
            var q = from e in GetIQueryable().AsExpandable()
                    join a in Db.GetIQueryable<PB_DesignDetail>() on e.Id equals a.ParentId into ea
                    from a in ea.DefaultIfEmpty()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_MaterialType>() on b.MaterialTypeId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_Project>() on e.ProjectId equals d.Id into ed
                    from d in ed.DefaultIfEmpty()
                    join f in Db.GetIQueryable<PB_Buildingnumber>() on e.BuildingNumberID equals f.Id into ef
                    from f in ef.DefaultIfEmpty()
                    select @select.Invoke(e, a, b, c, d, f);
            //筛选
            if (!ParentId.IsNullOrEmpty())
            {
                q = q.Where(w => w.Id == ParentId);
            }
            return await q.ToListAsync();
        }


        public async Task<PageResult<PB_DesignList>> GetDataSelectAsync(PageInput<DesignListConditionDTO> input)
        {
            var q = GetIQueryable();
            var search = input.Search;

            //筛选
            if (!search.Keyword.IsNullOrEmpty())
            {
                var keyword = $"%{search.Keyword}%";
                q = q.Where(x =>
                      EF.Functions.Like(x.ProjectName, keyword));
            }
            if (!search.Type.ToString().IsNullOrEmpty())
            {
                q = q.Where(x => x.Type == search.Type);
            }
            q = q.Where(h => _operator.Property.DeptIds.Contains(h.DeptId) && h.ExamineStatus == 2);
            return await q.GetPageResultAsync(input);
        }


        public async Task<PageResult<PB_MaterialSelectDTO>> GetDataSelectListAsync(PageInput<ConditionDTO> input, string ParentId)
        {
            var search = input.Search;
            Expression<Func<PB_DesignList, PB_DesignDetail, PB_Material, PB_MaterialType, PB_MaterialSelectDTO>> select = (a, b, c, d) => new PB_MaterialSelectDTO
            {
                MaterialId = b.MaterialId,
                Nums = b.Nums,
                MaterialName = c.Name,
                MaterialCode = c.Code,
                MaterialSpec = c.Spec,
                MaterialTypeName = d.Name,
                MaterialSimpleName = c.SimpleName
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_DesignDetail>() on a.Id equals b.ParentId into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Material>() on b.MaterialId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_MaterialType>() on c.MaterialTypeId equals d.Id into ad
                    from d in ad.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d);
            if (!search.Keyword.IsNullOrEmpty())
            {
                q = q.Where(m => m.ProjectName.Contains(search.Keyword));
            }
            q = q.Where(x => x.Id == ParentId);
            q = q.Where(b => _operator.Property.FactoryId.Contains(b.DeptId));
            return await q.GetPageResultAsync(input);
        }


        public async Task AddDataExlAsync(List<PB_DesignList> list)
        {
            await InsertAsync(list);
        }
        [DataAddLog(UserLogType.清单管理, "Name", "清单管理")]
        //[Transactional]
        public async Task AddData(PB_DesignDTO data)
        {
            string DesignID = IdHelper.GetId();
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

            //主表信息
            PB_DesignList _DesignList = new PB_DesignList
            {
                Id = DesignID,//主表id
                Code = data.Code,//清单编号
                ContractNo = data.ContractNo,//合同编号
                ProjectId = data.ProjectId,//所属项目
                Name = data.Name,//清单名称
                ProjectName = data.ProjectName,//工程名称
                StandsNums = data.StandsNums,//机位数量
                ProjectAddress = data.ProjectAddress,//工程地址
                LiftingMode = data.LiftingMode,//提升方式
                Salesman = data.Salesman,//业务负责人
                Phone0 = data.Phone0,//业务负责人联系方式
                StepHeight = data.StepHeight,//架体步高
                Receiver = data.Receiver,//接货负责人
                Phone1 = data.Phone1,//接货人联系方式
                Color = data.Color,//架 体颜色
                InDate = data.InDate,//进场时间
                OrderDate = data.OrderDate,//下单时间
                Style = data.Style,//网板样式
                Remarks = data.Remarks,//备注
                DeptId = bdata.DepartmentId,//组织id
                QrCode = h_DetailedList + "," + data.Id,//二维码
                Calculation = data.Calculation,//计算
                PicUrl = data.PicUrl,//配图url
                Examiner = data.Examiner,//审批
                Approver = data.Approver, //审批
                ApproverStatus = 0,//审批状态 0 待审批 1审批通过 2审批打回
                CreatorId = _operator?.UserId,//创建人
                ExamineStatus = 1,//清单审核状态：0-草稿；1-待审核；2-审核通过；3-打回；4-变更
                CreateTime = DateTime.Now,
                Deleted = false,
                IsPrint = false, //是否打印：0-未打印；1-已打印
                BuildingNumberID = data.BuildingNumberID,
                Type = data.Type,
                StepLevel = data.StepLevel,
            };

            //Base_OverFlowTaskInsert base_OverFlowTaskInsert = new Base_OverFlowTaskInsert();
            //base_OverFlowTaskInsert.BillId = DesignID;
            //base_OverFlowTaskInsert.BillType = "DesignList";
            //base_OverFlowTaskInsert.Level = 0;
            //await Db.InsertAsync(base_OverFlowTaskInsert);
            ////2022-03-04 朱柏清 项目执行过程明细
            PB_ProjectProcess pB_ProjectProcess = new PB_ProjectProcess
            {
                Id = IdHelper.GetId(),
                ProjectId = data.ProjectId,
                ProjectName = data.ProjectName,
                ProcessType = Db.GetIQueryable<Base_EnumItem>().Where(u => u.EnumCode.Contains("ProjectProcessType") && u.Name.Contains("设计清单")).FirstOrDefault().Value,
                BuildingnumberId = data.BuildingNumberID,
                BuildingnumberName = Db.GetIQueryable<PB_Buildingnumber>().Where(u => u.Id == data.BuildingNumberID).FirstOrDefault().Buildingnumber,
                Remarks = "新增",
                CreatorId = _operator.UserId,
                CreatorRealName = _operator.Property.RealName,
                CreateTime = DateTime.Now,
                OrderId = DesignID,
                Deleted = false,
            };
            await Db.InsertAsync<PB_ProjectProcess>(pB_ProjectProcess);
            PB_DesignListVersion pbdata = new PB_DesignListVersion
            {
                Id = IdHelper.GetId(),
                ParentId = DesignID,
                VersionNumber = 1,
                CreatorId = _operator.UserId,
                CreatorRealName = bdata.RealName,
                CreateTime = DateTime.Now,
                Deleted = false
            };
            await Db.InsertAsync(pbdata);

            //字表信息
            List<PB_DesignDetail> ListDesignDetail = new List<PB_DesignDetail>();
            #region 组装数据
            for (int i = 0; i < data.subMData.Count; i++)
            {
                double? Nums = 0;
                PB_DesignDetail pB_DesignDetail = new PB_DesignDetail();
                pB_DesignDetail.Id = IdHelper.GetId();//详情id
                pB_DesignDetail.ParentId = DesignID;//设计清单主表id
                pB_DesignDetail.MaterialId = data.subMData[i].Id;//物料id
                pB_DesignDetail.Nums = data.subMData[i].Nums;//设计数量
                pB_DesignDetail.RealNums = data.subMData[i].RealNums;//实发数量
                pB_DesignDetail.ShipmentNums = 0;
                pB_DesignDetail.Remarks = data.subMData[i].Remarks;//备注
                pB_DesignDetail.CreateTime = DateTime.Now;//创建时间
                pB_DesignDetail.CreatorId = _operator?.UserId; //创建人
                pB_DesignDetail.Deleted = false;//伪删除
                pB_DesignDetail.Weight = data.subMData[i].Weight;//理论重量
                pB_DesignDetail.VersionNumber = 1;  //版本号
                pB_DesignDetail.State = 0;  //状态
                pB_DesignDetail.Slot = data.subMData[i].Slot;

                pB_DesignDetail.OneStep = data.subMData[i].OneStep;
                if (data.subMData[i].OneStep<0)
                {
                    throw new BusException("第一步不能出现负数");
                }
                Nums += pB_DesignDetail.OneStep == null ? 0 : pB_DesignDetail.OneStep;
                pB_DesignDetail.TwoStep = data.subMData[i].TwoStep;
                if (data.subMData[i].TwoStep < 0)
                {
                    throw new BusException("第二步不能出现负数");
                }
                Nums += pB_DesignDetail.TwoStep == null ? 0 : pB_DesignDetail.TwoStep;
                pB_DesignDetail.ThreeStep = data.subMData[i].ThreeStep;
                if (data.subMData[i].ThreeStep < 0)
                {
                    throw new BusException("第三步不能出现负数");
                }
                Nums += pB_DesignDetail.ThreeStep == null ? 0 : pB_DesignDetail.ThreeStep;
                if (data.subMData[i].FourStep < 0)
                {
                    throw new BusException("第四步不能出现负数");
                }
                pB_DesignDetail.FourStep = data.subMData[i].FourStep;
                Nums += pB_DesignDetail.FourStep == null ? 0 : pB_DesignDetail.FourStep;
                if (data.subMData[i].FiveStep < 0)
                {
                    throw new BusException("第五步不能出现负数");
                }
                pB_DesignDetail.FiveStep = data.subMData[i].FiveStep;
                Nums += pB_DesignDetail.FiveStep == null ? 0 : pB_DesignDetail.FiveStep;
                if (data.subMData[i].SixStep < 0)
                {
                    throw new BusException("第六步不能出现负数");
                }
                pB_DesignDetail.SixStep = data.subMData[i].SixStep;
                Nums += pB_DesignDetail.SixStep == null ? 0 : pB_DesignDetail.SixStep;
                if (data.subMData[i].SevenStep < 0)
                {
                    throw new BusException("第七步不能出现负数");
                }
                pB_DesignDetail.SevenStep = data.subMData[i].SevenStep;
                Nums += pB_DesignDetail.SevenStep == null ? 0 : pB_DesignDetail.SevenStep;
                if (data.subMData[i].EightStep < 0)
                {
                    throw new BusException("第八步不能出现负数");
                }
                pB_DesignDetail.EightStep = data.subMData[i].EightStep;
                Nums += pB_DesignDetail.EightStep == null ? 0 : pB_DesignDetail.EightStep;
                if (data.subMData[i].NineStep < 0)
                {
                    throw new BusException("第九步不能出现负数");
                }
                pB_DesignDetail.NineStep = data.subMData[i].NineStep;
                Nums += pB_DesignDetail.NineStep == null ? 0 : pB_DesignDetail.NineStep;
                if (data.subMData[i].TenStep < 0)
                {
                    throw new BusException("第十步不能出现负数");
                }
                pB_DesignDetail.TenStep = data.subMData[i].TenStep;
                Nums += pB_DesignDetail.TenStep == null ? 0 : pB_DesignDetail.TenStep;
                pB_DesignDetail.ElevenStep = data.subMData[i].ElevenStep;
                pB_DesignDetail.TwelveStep = data.subMData[i].TwelveStep;
                pB_DesignDetail.ThirteenStep = data.subMData[i].ThirteenStep;
                pB_DesignDetail.FourteenStep = data.subMData[i].FourteenStep;
                pB_DesignDetail.FifteenStep = data.subMData[i].FifteenStep;
                if (Nums != pB_DesignDetail.RealNums)
                {
                    throw new BusException("步数设计数量与总设计数量不一致");
                }
                ListDesignDetail.Add(pB_DesignDetail);
            }
            await Db.InsertAsync(ListDesignDetail);
            await InsertAsync(_DesignList);
            //创建设计清单 反写发货计划明细状态为已创建设计清单
            var ProjectId = data.ProjectId;
            var BuilId = data.BuildingNumberID;
            string sqlMain = @" update PB_DeliveryPlanDetails set `States`=1    WHERE ProjectId='" + ProjectId + "' and BuildingId='" + BuilId + "'   and States !=3  || States!=2  ";
            await ExecuteSqlAsync(sqlMain);

            #endregion


            #region 设计清单工作流审批
            //string sqlMains = @" INSERT INTO  Base_OverFlowTask  VALUES ('" + DesignID + "','DesignList',0) ";
            //await ExecuteSqlAsync(sqlMains);
            ////审批人
            //List<string> ulist = new List<string>();
            //抄送人
            //List<string> ulistcc = new List<string>();
            //获取设计清单数据
            //StringBuilder sql = new StringBuilder();
            //sql.AppendLine("SELECT ");
            //sql.AppendLine("Base_OverFlow.Id,");
            //sql.AppendLine("Base_OverFlow.Content,");
            //sql.AppendLine("ifnull( Base_OverFlowTask.LEVEL, 0 ) LEVEL ");
            //sql.AppendLine("FROM ");
            //sql.AppendLine("PB_DesignList");
            //sql.AppendLine("INNER JOIN Base_OverFlowTask ON Base_OverFlowTask.BillId = PB_DesignList.Id");
            //sql.AppendLine("INNER JOIN Base_OverFlow ON Base_OverFlow.BillType = Base_OverFlowTask.BillType");
            //sql.AppendLine("WHERE ");
            //sql.AppendLine("PB_DesignList.Id = '" + DesignID + "'");
            //Util.Helper.DingInputDTO input = new Util.Helper.DingInputDTO();
            //string uids = "";
            //var flowMob = await Db.GetListBySqlAsync<CurrentOverFlowDTO>(sql.ToString());
            //JArray farrMob = JArray.Parse(flowMob[0].Content);
            //JObject _objMob = JObject.Parse(farrMob[flowMob[0].Level].ToString());


            //JArray usrMob = JArray.Parse(farrMob[0]["Assignees"]["UserId"].ToString());
            //var list = await Db.GetIQueryable<PB_DesignList>().Where(m => m.Id == DesignID).FirstOrDefaultAsync();
            //var ProjectName = await Db.GetIQueryable<PB_Project>().Where(m => m.Id == list.ProjectId).FirstOrDefaultAsync();
            //var Buildingnumber = await Db.GetIQueryable<PB_Buildingnumber>().Where(m => m.Id == list.BuildingNumberID).FirstOrDefaultAsync();
            //input.Str = $"设计清单:{ProjectName.Name}{Buildingnumber.Buildingnumber}请审批" + DateTime.Now.ToString("");
            //string url = "eapp://pages/info/info?billid=" + DesignID + "&title=" + _objMob["StartState"]["Name"] + "&btn=" + _objMob["Action"]["Name"].ToString() + "&id=" + flowMob[0].Id + "";
            //input.MessgUrl = url;
            //input.BillId = DesignID;
            //if (usrMob.Count > 0)
            //{
            //    foreach (var u in usrMob)
            //    {
            //        uids += "'" + u + "',";
            //    }
            //    var emps = await Db.GetListBySqlAsync<Base_User>("SELECT * FROM Base_User WHERE Id IN (" + uids.Substring(0, uids.Length - 1) + ")");
            //    foreach (var e in emps)
            //    {
            //        ulist.Add(e.DingUserId);
            //    }
            //}
            //input.ExecutorIds = ulist;
            //DingHelper.sendMessage(input);
            //获取抄送人
            //string uidscc = "";
            //JArray usrMobCC = JArray.Parse(farrMob[0]["Assignees"]["PersonId"].ToString());
            //Util.Helper.DingInputDTO inputcc = new Util.Helper.DingInputDTO();
            //inputcc.Str = $"设计清单:{ProjectName.Name}{Buildingnumber.Buildingnumber}" + DateTime.Now.ToString("");
            //string BliiType = "DesignList";
            //string urlcc = $"eapp://pages/infoView/infoView?BillId={DesignID}&UserType=1&BillType={BliiType}&Type=0";
            //inputcc.MessgUrl = urlcc;
            //inputcc.BillId = DesignID;
            //if (usrMobCC.Count > 0)
            //{
            //    foreach (var u in usrMobCC)
            //    {
            //        uidscc += "'" + u + "',";
            //    }
            //    var emps = await Db.GetListBySqlAsync<Base_User>("SELECT * FROM Base_User WHERE Id IN (" + uidscc.Substring(0, uidscc.Length - 1) + ")");
            //    foreach (var e in emps)
            //    {
            //        ulistcc.Add(e.DingUserId);
            //    }

            //    inputcc.ExecutorIds = ulistcc;
            //    DingHelper.sendMessage(inputcc);

            //}
            #endregion 设计器清单工作流审批
        }
        [DataAddLog(UserLogType.清单管理, "Name", "清单管理")]
        [Transactional]
        public async Task UpdateData(PB_DesignDTO data)
        {
            //主表信息
            PB_DesignList _DesignList = new PB_DesignList
            {
                Id = data.Id,//主表id
                Code = data.Code,//清单编号
                ContractNo = data.ContractNo,//合同编号
                ProjectId = data.ProjectId,//所属项目
                Name = data.Name,//清单名称
                ProjectName = data.ProjectName,//工程名称
                StandsNums = data.StandsNums,//机位数量
                ProjectAddress = data.ProjectAddress,//工程地址
                LiftingMode = data.LiftingMode,//提升方式
                Salesman = data.Salesman,//业务负责人
                Phone0 = data.Phone0,//业务负责人联系方式
                StepHeight = data.StepHeight,//架体步高
                Receiver = data.Receiver,//接货负责人
                Phone1 = data.Phone1,//接货人联系方式
                Color = data.Color,//架 体颜色
                InDate = data.InDate,//进场时间
                OrderDate = data.OrderDate,//下单时间
                Style = data.Style,//网板样式
                Remarks = data.Remarks,//备注
                DeptId = data.DeptId,//组织id
                QrCode = h_DetailedList + "," + data.Id,//二维码
                Calculation = data.Calculation,//计算
                PicUrl = data.PicUrl,//配图url
                Examiner = data.Examiner,//审批
                Approver = data.Approver, //审批
                ApproverStatus = 0,//审批状态 0 待审批 1审批通过 2审批打回
                CreatorId = _operator?.UserId,//创建人
                ExamineStatus = 1,//审核状态 0 待审核 1审核通过 2打回
                CreateTime = DateTime.Now,
                Deleted = data.Deleted,
                BuildingNumberID = data.BuildingNumberID,
                IsPrint = false,   //是否打印：0-未打印；1-已打印
                Type = data.Type,
            };
            await UpdateAsync(_DesignList);
            //2022-03-04 朱柏清 项目执行过程明细
            PB_ProjectProcess pB_ProjectProcess = new PB_ProjectProcess
            {
                Id = IdHelper.GetId(),
                ProjectId = data.ProjectId,
                ProjectName = data.ProjectName,
                ProcessType = Db.GetIQueryable<Base_EnumItem>().Where(u => u.EnumCode.Contains("ProjectProcessType") && u.Name.Contains("设计清单")).FirstOrDefault().Value,
                BuildingnumberId = data.BuildingNumberID,
                BuildingnumberName = Db.GetIQueryable<PB_Buildingnumber>().Where(u => u.Id == data.BuildingNumberID).FirstOrDefault().Buildingnumber,
                Remarks = "修改",
                CreatorId = _operator.UserId,
                CreatorRealName = _operator.Property.RealName,
                CreateTime = DateTime.Now,
                OrderId = data.Id,
                Deleted = false,
            };
            await Db.InsertAsync<PB_ProjectProcess>(pB_ProjectProcess);
            //操作之前先清空所有数据

            var intrunt = await ExecuteSqlAsync("DELETE FROM PB_DesignDetail WHERE ParentId in ('" + data.Id + "')");
            //
            List<PB_DesignDetail> ListDesignDetail = new List<PB_DesignDetail>();
            #region 组装数据
            for (int i = 0; i < data.subMData.Count; i++)
            {
                PB_DesignDetail pB_DesignDetail = new PB_DesignDetail();
                pB_DesignDetail.Id = IdHelper.GetId();//详情id
                pB_DesignDetail.ParentId = data.Id;//设计清单主表id
                pB_DesignDetail.MaterialId = data.subMData[i].Id;//物料id
                pB_DesignDetail.Nums = data.subMData[i].Nums;//设计数量
                pB_DesignDetail.RealNums = data.subMData[i].RealNums;//实发数量
                pB_DesignDetail.Remarks = data.subMData[i].Remarks;//备注
                pB_DesignDetail.CreateTime = DateTime.Now;//创建时间
                pB_DesignDetail.CreatorId = _operator?.UserId; //创建人
                pB_DesignDetail.Deleted = false;//伪删除
                pB_DesignDetail.Weight = data.subMData[i].Weight;//理论重量
                pB_DesignDetail.Slot = data.subMData[i].Slot;
                ListDesignDetail.Add(pB_DesignDetail);
            }
            await Db.InsertAsync(ListDesignDetail);
            #endregion

        }

        public async Task AddMaterialData(SaveMaterialData data)
        {
            //字表信息
            List<PB_DesignDetail> ListDesignDetail = new List<PB_DesignDetail>();
            #region 组装数据
            for (int i = 0; i < data.subMData.Count; i++)
            {
                double? nums = 0;
                PB_DesignDetail pB_DesignDetail = new PB_DesignDetail();
                pB_DesignDetail.Id = IdHelper.GetId();//详情id
                pB_DesignDetail.ParentId = data.PId;//设计清单主表id
                pB_DesignDetail.MaterialId = data.subMData[i].Id;//物料id
                pB_DesignDetail.Nums = data.subMData[i].Nums;//设计数量
                pB_DesignDetail.RealNums = data.subMData[i].RealNums;//实发数量
                pB_DesignDetail.Remarks = data.subMData[i].Remarks;//备注
                pB_DesignDetail.CreateTime = DateTime.Now;//创建时间
                pB_DesignDetail.CreatorId = _operator?.UserId; //创建人
                pB_DesignDetail.Deleted = false;//伪删除
                pB_DesignDetail.Weight = data.subMData[i].Weight;//理论重量
                pB_DesignDetail.State = 0;  //状态
                pB_DesignDetail.Slot = data.subMData[i].Slot;
                pB_DesignDetail.OneStep = data.subMData[i].OneStep;
                nums += pB_DesignDetail.OneStep == null ? 0 : pB_DesignDetail.OneStep;
                pB_DesignDetail.TwoStep = data.subMData[i].TwoStep;
                nums += pB_DesignDetail.TwoStep == null ? 0 : pB_DesignDetail.TwoStep;
                pB_DesignDetail.ThreeStep = data.subMData[i].ThreeStep;
                nums += pB_DesignDetail.ThreeStep == null ? 0 : pB_DesignDetail.ThreeStep;
                pB_DesignDetail.FourStep = data.subMData[i].FourStep;
                nums += pB_DesignDetail.FourStep == null ? 0 : pB_DesignDetail.FourStep;
                pB_DesignDetail.FiveStep = data.subMData[i].FiveStep;
                nums += pB_DesignDetail.FiveStep == null ? 0 : pB_DesignDetail.FiveStep;
                pB_DesignDetail.SixStep = data.subMData[i].SixStep;
                nums += pB_DesignDetail.SixStep == null ? 0 : pB_DesignDetail.SixStep;
                pB_DesignDetail.SevenStep = data.subMData[i].SevenStep;
                nums += pB_DesignDetail.SevenStep == null ? 0 : pB_DesignDetail.SevenStep;
                pB_DesignDetail.EightStep = data.subMData[i].EightStep;
                nums += pB_DesignDetail.EightStep == null ? 0 : pB_DesignDetail.EightStep;
                pB_DesignDetail.NineStep = data.subMData[i].NineStep;
                nums += pB_DesignDetail.NineStep == null ? 0 : pB_DesignDetail.NineStep;
                pB_DesignDetail.TenStep = data.subMData[i].TenStep;
                nums += pB_DesignDetail.TenStep == null ? 0 : pB_DesignDetail.TenStep;
                pB_DesignDetail.ElevenStep = data.subMData[i].ElevenStep;
                pB_DesignDetail.TwelveStep = data.subMData[i].TwelveStep;
                pB_DesignDetail.ThirteenStep = data.subMData[i].ThirteenStep;
                pB_DesignDetail.FourteenStep = data.subMData[i].FourteenStep;
                pB_DesignDetail.FifteenStep = data.subMData[i].FifteenStep;
                if (pB_DesignDetail.State == 1 || pB_DesignDetail.State == 2)
                {
                    pB_DesignDetail.FifteenStep = data.subMData[i].RealNums;
                }
                ListDesignDetail.Add(pB_DesignDetail);
            }
            await Db.InsertAsync(ListDesignDetail);
            //2022-03-04 朱柏清 项目执行过程明细
            PB_DesignList pB_DesignList = Db.GetIQueryable<PB_DesignList>().Where(s => s.Id == data.PId).FirstOrDefault();
            PB_ProjectProcess pB_ProjectProcess = new PB_ProjectProcess
            {
                Id = IdHelper.GetId(),
                ProjectId = pB_DesignList.ProjectId,
                ProjectName = pB_DesignList.ProjectName,
                ProcessType = Db.GetIQueryable<Base_EnumItem>().Where(u => u.EnumCode.Contains("ProjectProcessType") && u.Name.Contains("设计清单")).FirstOrDefault().Value,
                BuildingnumberId = pB_DesignList.BuildingNumberID,
                BuildingnumberName = Db.GetIQueryable<PB_Buildingnumber>().Where(u => u.Id == pB_DesignList.BuildingNumberID).FirstOrDefault().Buildingnumber,
                Remarks = "修改",
                CreatorId = _operator.UserId,
                CreatorRealName = _operator.Property.RealName,
                CreateTime = DateTime.Now,
                OrderId = pB_DesignList.Id,
                Deleted = false,
            };
            await Db.InsertAsync<PB_ProjectProcess>(pB_ProjectProcess);
            #endregion
        }

        /// <summary>
        /// 编辑设计清单下的物料详情添加
        /// </summary>
        /// <param name="data">保存设计清单及明细</param>
        /// <returns></returns>

        public async Task UpdateMaterialData(SaveMaterialData data)
        {
            //子表信息
            List<PB_DesignDetail> ListDesignDetail = new List<PB_DesignDetail>();
            var parentData = Db.GetIQueryable<PB_DesignList>().Where(s => s.Id == data.PId).FirstOrDefault();
            var detailDatalist = await Db.GetIQueryable<PB_DesignDetail>().Where(s => s.ParentId == data.PId).ToListAsync();

            //变更设计清单，朱柏清，2022-03-08
            if (parentData.ExamineStatus == 4)
            {
                var qdata = await Db.GetIQueryable<PB_DesignListVersion>().Where(x => x.ParentId == data.PId).OrderByDescending(x => x.VersionNumber).FirstOrDefaultAsync();
                for (int i = 0; i < data.subMData.Count; i++)
                {
                    //新增明细行
                    if (data.subMData[i].SubId == null)
                    {
                       
                        PB_DesignDetail pB_DesignDetail = new PB_DesignDetail();
                        pB_DesignDetail.Id = IdHelper.GetId();//详情id
                        pB_DesignDetail.ParentId = data.PId;//设计清单主表id
                        pB_DesignDetail.MaterialId = data.subMData[i].Id;//物料id
                        pB_DesignDetail.Nums = data.subMData[i].Nums < 0 ? -data.subMData[i].Nums : data.subMData[i].Nums;//设计数量
                        pB_DesignDetail.RealNums = data.subMData[i].RealNums < 0 ? -data.subMData[i].RealNums : data.subMData[i].RealNums;//实发数量
                        pB_DesignDetail.Remarks = data.subMData[i].Remarks;//备注
                        pB_DesignDetail.CreateTime = DateTime.Now;//创建时间
                        pB_DesignDetail.CreatorId = _operator?.UserId; //创建人
                        pB_DesignDetail.Deleted = false;//伪删除
                        pB_DesignDetail.Weight = data.subMData[i].Weight;//理论重量
                        pB_DesignDetail.Slot = data.subMData[i].Slot;//行数
                        pB_DesignDetail.VersionNumber = qdata.VersionNumber;   //清单版本号
                        pB_DesignDetail.State = data.subMData[i].RealNums < 0 ? 2 : 1;
                        pB_DesignDetail.OneStep = data.subMData[i].OneStep;
                        pB_DesignDetail.TwoStep = data.subMData[i].TwoStep;
                        pB_DesignDetail.ThreeStep = data.subMData[i].ThreeStep;
                        pB_DesignDetail.FourStep = data.subMData[i].FourStep;
                        pB_DesignDetail.FiveStep = data.subMData[i].FiveStep;
                        pB_DesignDetail.SixStep = data.subMData[i].SixStep;
                        pB_DesignDetail.SevenStep = data.subMData[i].SevenStep;
                        pB_DesignDetail.EightStep = data.subMData[i].EightStep;
                        pB_DesignDetail.NineStep = data.subMData[i].NineStep;
                        pB_DesignDetail.TenStep = data.subMData[i].TenStep;
                        pB_DesignDetail.ElevenStep = data.subMData[i].ElevenStep;
                        pB_DesignDetail.TwelveStep = data.subMData[i].TwelveStep;
                        pB_DesignDetail.ThirteenStep = data.subMData[i].ThirteenStep;
                        pB_DesignDetail.FourteenStep = data.subMData[i].FourteenStep;
                        pB_DesignDetail.FifteenStep = data.subMData[i].FifteenStep;
                       
                        if (pB_DesignDetail.State == 1)
                        {
                            pB_DesignDetail.FifteenStep = data.subMData[i].RealNums;
                        }
                        else  if(pB_DesignDetail.State==2){
                            double? jianshaonuns = 0;
                            //判断是否存在基础版物料信息
                            var dbmater =await Db.GetIQueryable<PB_DesignDetail>().Where(m => m.ParentId == data.PId && m.MaterialId == pB_DesignDetail.MaterialId).FirstOrDefaultAsync();
                            if (dbmater!=null) {
                                //获取第十五步补加的信息
                                var pB_DesignDetail2 = detailDatalist.Where(m => m.State < 2 && m.MaterialId == pB_DesignDetail.MaterialId).ToList();
                                var Wuliao = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, FifteenStep = x.Sum(p => p.FifteenStep) }).FirstOrDefault();
                                //获取第十五步变更减少sum的总数
                                var pB_DesignDetailDelete = detailDatalist.Where(m => m.State == 2 && m.MaterialId == pB_DesignDetail.MaterialId).ToList();
                                var Wuliao2 = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, FifteenStep = x.Sum(p => p.FifteenStep) }).FirstOrDefault();
                                //获取第十五步数量效验
                                var FifteenStepNums = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, FifteenStep = x.Sum(p => p.FifteenStep) }).FirstOrDefault();
                                var FifteenStepReady = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, FifteenStepReady = x.Sum(p => p.FifteenStepReady) }).FirstOrDefault();
                                var FifteenStepDeleteNums = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, FifteenStep = x.Sum(p => p.FifteenStep) }).FirstOrDefault();
                                var FifteenStepDeleteReady = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, FifteenStepReady = x.Sum(p => p.FifteenStepReady) }).FirstOrDefault();
                                double? numsFifteenStep = (FifteenStepNums.FifteenStep - FifteenStepReady.FifteenStepReady) - ((FifteenStepDeleteNums == null ? 0 : FifteenStepDeleteNums.FifteenStep) - (FifteenStepDeleteReady == null ? 0 : FifteenStepDeleteReady.FifteenStepReady));
                                jianshaonuns += (Wuliao == null ? 0 : Wuliao.FifteenStep)-( Wuliao2 == null ? 0 : Wuliao2.FifteenStep);
                           


                                //获取第十步数量效验
                                var TenStepNums = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, TenStep = x.Sum(p => p.TenStep) }).FirstOrDefault();
                                var TenStepReady = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, TenStepReady = x.Sum(p => p.TenStepReady) }).FirstOrDefault();
                                var TenStepDeleteNums = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, TenStep = x.Sum(p => p.TenStep) }).FirstOrDefault();
                                var TenStepDeleteReady = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, TenStepReady = x.Sum(p => p.TenStepReady) }).FirstOrDefault();
                                double? numsTenStep = (TenStepNums == null ? 0 : TenStepNums.TenStep) -  (TenStepDeleteNums == null ? 0 : TenStepDeleteNums.TenStep) ;

                                //获取第九步数量效验 
                                var NineStepNums = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, NineStep = x.Sum(p => p.NineStep) }).FirstOrDefault();
                                var NineStepReady = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, NineStepReady = x.Sum(p => p.NineStepReady) }).FirstOrDefault();
                                var NineStepDeleteNums = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, NineStep = x.Sum(p => p.NineStep) }).FirstOrDefault();
                                var NineStepReadyDelete = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, NineStepReady = x.Sum(p => p.NineStepReady) }).FirstOrDefault();
                                double? numsNineStep = (NineStepNums == null ? 0 : NineStepNums.NineStep) -  - (NineStepDeleteNums == null ? 0 : NineStepDeleteNums.NineStep) ;


                                //获取第八步数量效验
                                var EightStepNums = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, EightStep = x.Sum(p => p.EightStep) }).FirstOrDefault();
                                var EightStepReady = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, EightStepReady = x.Sum(p => p.EightStepReady) }).FirstOrDefault();
                                var EightStepDeleteNums = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, EightStep = x.Sum(p => p.EightStep) }).FirstOrDefault();
                                var EightStepReadyDelete = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, EightStepReady = x.Sum(p => p.EightStepReady) }).FirstOrDefault();
                                double? numsEightStep = ((EightStepNums == null ? 0 : EightStepNums.EightStep) - (EightStepReady == null ? 0 : EightStepReady.EightStepReady)) - ((EightStepDeleteNums == null ? 0 : EightStepDeleteNums.EightStep) - (EightStepReadyDelete == null ? 0 : EightStepReadyDelete.EightStepReady));



                                //获取七步数量效验
                                var SevenStepNums = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, SevenStep = x.Sum(p => p.SevenStep) }).FirstOrDefault();
                                var SevenStepReady = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, SevenStepReady = x.Sum(p => p.SevenStepReady) }).FirstOrDefault();
                                var SevenStepDeleteNums = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, SevenStep = x.Sum(p => p.SevenStep) }).FirstOrDefault();
                                var SevenStepReadyDelete = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, SevenStepReady = x.Sum(p => p.SevenStepReady) }).FirstOrDefault();
                                double? numsSevenStep = ((SevenStepNums == null ? 0 : SevenStepNums.SevenStep) - (SevenStepReady == null ? 0 : SevenStepReady.SevenStepReady)) - ((SevenStepDeleteNums == null ? 0 : SevenStepDeleteNums.SevenStep) - (SevenStepReadyDelete == null ? 0 : SevenStepReadyDelete.SevenStepReady));

                                //获取第六步数量效验
                                var SixStepNums = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, SixStep = x.Sum(p => p.SixStep) }).FirstOrDefault();
                                var SixStepReady = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, SixStepReady = x.Sum(p => p.SixStepReady) }).FirstOrDefault();
                                var SixStepDeleteNums = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, SixStep = x.Sum(p => p.SixStep) }).FirstOrDefault();
                                var SixStepReadyDelete = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, SixStepReady = x.Sum(p => p.SixStepReady) }).FirstOrDefault();
                                double? numsSixStep = ((SevenStepNums == null ? 0 : SixStepNums.SixStep) - (SixStepReady == null ? 0 : SixStepReady.SixStepReady)) - ((SevenStepDeleteNums == null ? 0 : SixStepDeleteNums.SixStep) - (SixStepReadyDelete == null ? 0 : SixStepReadyDelete.SixStepReady));


                                //获取第五步数量效验
                                var FiveStepNums = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, FiveStep = x.Sum(p => p.FiveStep) }).FirstOrDefault();
                                var FiveStepReady = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, FiveStepReady = x.Sum(p => p.FiveStepReady) }).FirstOrDefault();
                                var FiveStepDeleteNums = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, FiveStep = x.Sum(p => p.FiveStep) }).FirstOrDefault();
                                var FiveStepReadyDelete = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, FiveStepReady = x.Sum(p => p.FiveStepReady) }).FirstOrDefault();
                                double? numsFiveStep = ((FiveStepNums == null ? 0 : FiveStepNums.FiveStep) - (FiveStepReady == null ? 0 : FiveStepReady.FiveStepReady)) - ((FiveStepDeleteNums == null ? 0 : FiveStepDeleteNums.FiveStep) - (FiveStepReadyDelete == null ? 0 : FiveStepReadyDelete.FiveStepReady));

                                //获取第四步数量效验
                                var FourStepNums = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, FourStep = x.Sum(p => p.FourStep) }).FirstOrDefault();
                                var FourStepReady = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, FourStepReady = x.Sum(p => p.FourStepReady) }).FirstOrDefault();
                                var FourStepDeleteNums = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, FourStep = x.Sum(p => p.FourStep) }).FirstOrDefault();
                                var FourStepReadyDelete = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, FourStepReady = x.Sum(p => p.FourStepReady) }).FirstOrDefault();
                                double? numsFourStep = ((FourStepNums == null ? 0 : FourStepNums.FourStep) - (FourStepReady == null ? 0 : FourStepReady.FourStepReady)) - ((FiveStepDeleteNums == null ? 0 : FourStepDeleteNums.FourStep) - (FourStepReadyDelete == null ? 0 : FourStepReadyDelete.FourStepReady));

                                //获取第三步数量效验
                                var ThreeStepNums = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, ThreeStep = x.Sum(p => p.ThreeStep) }).FirstOrDefault();
                                var ThreeStepReady = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, ThreeStepReady = x.Sum(p => p.ThreeStepReady) }).FirstOrDefault();
                                var ThreeStepDeleteNums = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, ThreeStep = x.Sum(p => p.ThreeStep) }).FirstOrDefault();
                                var ThreeStepReadyDelete = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, ThreeStepReady = x.Sum(p => p.ThreeStepReady) }).FirstOrDefault();
                                double? numsThreeStep = ((FourStepNums == null ? 0 : ThreeStepNums.ThreeStep) - (ThreeStepReady == null ? 0 : ThreeStepReady.ThreeStepReady)) - ((ThreeStepDeleteNums == null ? 0 : ThreeStepDeleteNums.ThreeStep) - (ThreeStepReadyDelete == null ? 0 : ThreeStepReadyDelete.ThreeStepReady));
                                //获取第二步数量效验
                                var TwoStepNums = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, TwoStep = x.Sum(p => p.TwoStep) }).FirstOrDefault();
                                var TwoStepReady = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, TwoStepReady = x.Sum(p => p.TwoStepReady) }).FirstOrDefault();
                                var TwoStepDeleteNums = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, TwoStep = x.Sum(p => p.TwoStep) }).FirstOrDefault();
                                var TwoStepReadyDelete = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, TwoStepReady = x.Sum(p => p.TwoStepReady) }).FirstOrDefault();
                                double? numsTwoStep = ((TwoStepNums == null ? 0 : TwoStepNums.TwoStep) - (TwoStepReady == null ? 0 : TwoStepReady.TwoStepReady)) - ((TwoStepDeleteNums == null ? 0 : TwoStepDeleteNums.TwoStep) - (TwoStepReadyDelete == null ? 0 : TwoStepReadyDelete.TwoStepReady));

                                //获取第一步数量效验
                                var OneStepNums = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, OneStep = x.Sum(p => p.OneStep) }).FirstOrDefault();
                                var OneStepReady = pB_DesignDetail2.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, OneStepReady = x.Sum(p => p.OneStepReady) }).FirstOrDefault();
                                var OneStepDeleteNums = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, OneStep = x.Sum(p => p.OneStep) }).FirstOrDefault();
                                var OneStepReadyDelete = pB_DesignDetailDelete.GroupBy(x => new { x.MaterialId }).Select(x => new { MaterialId = x.Key.MaterialId, OneStepReady = x.Sum(p => p.OneStepReady) }).FirstOrDefault();
                                double? numsOneStep = ((OneStepNums == null ? 0 : OneStepNums.OneStep) - (OneStepReady == null ? 0 : OneStepReady.OneStepReady)) - ((OneStepDeleteNums == null ? 0 : OneStepDeleteNums.OneStep) - (OneStepReadyDelete == null ? 0 : OneStepReadyDelete.OneStepReady));

                                double? CalculateSum = numsTenStep + numsNineStep + numsEightStep + numsSevenStep + numsSixStep + numsFiveStep + numsFourStep + numsThreeStep + numsTwoStep + numsOneStep;
                                if (CalculateSum < pB_DesignDetail.RealNums)
                                {
                                    double? jian = jianshaonuns + CalculateSum;
                                    double? nums = (pB_DesignDetail.RealNums - CalculateSum);
                                    var jiannums = numsFifteenStep + CalculateSum;
                                    if (jian< pB_DesignDetail.RealNums)
                                    {
                                        var mater = Db.GetIQueryable<PB_Material>().Where(s => s.Id == pB_DesignDetail.MaterialId).FirstOrDefault();
                                        throw new BusException($"{mater.Name}减少数量超出或已备货!");
                                    }
                                    else
                                    {
                                        pB_DesignDetail.FifteenStep = nums;
                                    }


                                }

                                double? Value = numsTenStep;
                                double? surplus = 0;
                                surplus = Value - pB_DesignDetail.RealNums;
                                if (surplus < 0)
                                {

                                  

                                    if (numsTenStep > 0 && surplus < 0)
                                    {
                                        surplus = numsTenStep >= -surplus ? -surplus : surplus + numsTenStep;
                                        pB_DesignDetail.TenStep = surplus >= 0 ? surplus : numsTenStep;

                                    }

                                    if (numsNineStep > 0 && surplus < 0)
                                    {

                                        surplus = numsNineStep >= -surplus ? -surplus : surplus + numsNineStep;
                                        pB_DesignDetail.NineStep = surplus >= 0 ? surplus : numsNineStep;

                                    }

                                    if (numsEightStep > 0 && surplus < 0)
                                    {

                                        surplus = numsEightStep >= -surplus ? -surplus : surplus + numsEightStep;
                                        pB_DesignDetail.EightStep = surplus >= 0 ? surplus : numsEightStep;

                                    }
                                    if (numsSevenStep > 0 && surplus < 0)
                                    {

                                        surplus = numsSevenStep >= -surplus ? -surplus : surplus + numsSevenStep;
                                        pB_DesignDetail.SevenStep = surplus >= 0 ? surplus : numsSevenStep;

                                    }
                                    if (numsSixStep > 0 && surplus < 0)
                                    {

                                        surplus = numsSixStep >= -surplus ? -surplus : surplus + numsSixStep;
                                        pB_DesignDetail.SixStep = surplus >= 0 ? surplus : numsSixStep;
                                    }
                                    if (numsFiveStep > 0 && surplus < 0)
                                    {

                                        surplus = numsFiveStep >= -surplus ? -surplus : surplus + numsFiveStep;
                                        pB_DesignDetail.FiveStep = surplus >= 0 ? surplus : numsFiveStep;
                                    }
                                    if (numsFourStep > 0 && surplus < 0)
                                    {
                                        surplus = numsFourStep >= -surplus ? -surplus : surplus + numsFourStep;
                                        pB_DesignDetail.FourStep = surplus >= 0 ? surplus : numsFourStep;
                                    }
                                    if (numsThreeStep > 0 && surplus < 0)
                                    {
                                        surplus = numsThreeStep >= -surplus ? -surplus : surplus + numsThreeStep;
                                        pB_DesignDetail.ThreeStep = surplus >= 0 ? surplus : numsThreeStep;
                                    }
                                    if (numsTwoStep > 0 && surplus < 0)
                                    {
                                        surplus = numsTwoStep >= -surplus ? -surplus : surplus + numsTwoStep;
                                        pB_DesignDetail.TwoStep = surplus >= 0 ? surplus : numsTwoStep;
                                    }
                                    if (numsOneStep > 0 && surplus < 0)
                                    {
                                        surplus = numsOneStep >= -surplus ? -surplus : surplus + numsOneStep;
                                        pB_DesignDetail.OneStep = surplus >= 0 ? surplus : numsOneStep;
                                    }



                                }
                            }
                        }
                        ListDesignDetail.Add(pB_DesignDetail);
                    }
                }
              
                if (ListDesignDetail != null)
                {
                    await Db.InsertAsync(ListDesignDetail);
                }
            }
            else
            {
              
                #region 组装数据
                for (int i = 0; i < data.subMData.Count; i++)
                {
                    double? nums = 0;
                    PB_DesignDetail pB_DesignDetail = new PB_DesignDetail();
                    pB_DesignDetail.Id = IdHelper.GetId();//详情id
                    pB_DesignDetail.ParentId = data.PId;//设计清单主表id
                    pB_DesignDetail.MaterialId = data.subMData[i].Id;//物料id
                    pB_DesignDetail.Nums = data.subMData[i].Nums;//设计数量
                    pB_DesignDetail.RealNums = data.subMData[i].RealNums;//实发数量
                    pB_DesignDetail.Remarks = data.subMData[i].Remarks;//备注
                    pB_DesignDetail.CreateTime = DateTime.Now;//创建时间
                    pB_DesignDetail.CreatorId = _operator?.UserId; //创建人
                    pB_DesignDetail.Deleted = false;//伪删除
                    pB_DesignDetail.Weight = data.subMData[i].Weight;//理论重量
                    pB_DesignDetail.Slot = data.subMData[i].Slot;//行数
                    pB_DesignDetail.VersionNumber = 1;   //清单版本号
                    pB_DesignDetail.State = 0;
                    pB_DesignDetail.Slot = data.subMData[i].Slot;
                    pB_DesignDetail.OneStep = data.subMData[i].OneStep;
                    nums += pB_DesignDetail.OneStep == null ? 0 : pB_DesignDetail.OneStep;
                    pB_DesignDetail.TwoStep = data.subMData[i].TwoStep;
                    nums += pB_DesignDetail.TwoStep == null ? 0 : pB_DesignDetail.TwoStep;
                    pB_DesignDetail.ThreeStep = data.subMData[i].ThreeStep;
                    nums += pB_DesignDetail.ThreeStep == null ? 0 : pB_DesignDetail.ThreeStep;
                    pB_DesignDetail.FourStep = data.subMData[i].FourStep;
                    nums += pB_DesignDetail.FourStep == null ? 0 : pB_DesignDetail.FourStep;
                    pB_DesignDetail.FiveStep = data.subMData[i].FiveStep;
                    nums += pB_DesignDetail.FiveStep == null ? 0 : pB_DesignDetail.FiveStep;
                    pB_DesignDetail.SixStep = data.subMData[i].SixStep;
                    nums += pB_DesignDetail.SixStep == null ? 0 : pB_DesignDetail.SixStep;
                    pB_DesignDetail.SevenStep = data.subMData[i].SevenStep;
                    nums += pB_DesignDetail.SevenStep == null ? 0 : pB_DesignDetail.SevenStep;
                    pB_DesignDetail.EightStep = data.subMData[i].EightStep;
                    nums += pB_DesignDetail.EightStep == null ? 0 : pB_DesignDetail.EightStep;
                    pB_DesignDetail.NineStep = data.subMData[i].NineStep;
                    nums += pB_DesignDetail.NineStep == null ? 0 : pB_DesignDetail.NineStep;
                    pB_DesignDetail.TenStep = data.subMData[i].TenStep;
                    nums += pB_DesignDetail.TenStep == null ? 0 : pB_DesignDetail.TenStep;
                    pB_DesignDetail.ElevenStep = data.subMData[i].ElevenStep;
                    pB_DesignDetail.TwelveStep = data.subMData[i].TwelveStep;
                    pB_DesignDetail.ThirteenStep = data.subMData[i].ThirteenStep;
                    pB_DesignDetail.FourteenStep = data.subMData[i].FourteenStep;
                    pB_DesignDetail.FifteenStep = data.subMData[i].FifteenStep;
                    if (nums != pB_DesignDetail.RealNums)
                    {
                        throw new BusException("步数设计数量与总设计数量不一致");
                    }
                    double? Nums = 0;
                    if (data.subMData[i].OneStep < 0)
                    {
                        throw new BusException("第一步不能出现负数");
                    }
                    Nums += pB_DesignDetail.OneStep == null ? 0 : pB_DesignDetail.OneStep;
                    pB_DesignDetail.TwoStep = data.subMData[i].TwoStep;
                    if (data.subMData[i].TwoStep < 0)
                    {
                        throw new BusException("第二步不能出现负数");
                    }
                    Nums += pB_DesignDetail.TwoStep == null ? 0 : pB_DesignDetail.TwoStep;
                    pB_DesignDetail.ThreeStep = data.subMData[i].ThreeStep;
                    if (data.subMData[i].ThreeStep < 0)
                    {
                        throw new BusException("第三步不能出现负数");
                    }
                    Nums += pB_DesignDetail.ThreeStep == null ? 0 : pB_DesignDetail.ThreeStep;
                    if (data.subMData[i].FourStep < 0)
                    {
                        throw new BusException("第四步不能出现负数");
                    }
                    pB_DesignDetail.FourStep = data.subMData[i].FourStep;
                    Nums += pB_DesignDetail.FourStep == null ? 0 : pB_DesignDetail.FourStep;
                    if (data.subMData[i].FiveStep < 0)
                    {
                        throw new BusException("第五步不能出现负数");
                    }
                    pB_DesignDetail.FiveStep = data.subMData[i].FiveStep;
                    Nums += pB_DesignDetail.FiveStep == null ? 0 : pB_DesignDetail.FiveStep;
                    if (data.subMData[i].SixStep < 0)
                    {
                        throw new BusException("第六步不能出现负数");
                    }
                    pB_DesignDetail.SixStep = data.subMData[i].SixStep;
                    Nums += pB_DesignDetail.SixStep == null ? 0 : pB_DesignDetail.SixStep;
                    if (data.subMData[i].SevenStep < 0)
                    {
                        throw new BusException("第七步不能出现负数");
                    }
                    pB_DesignDetail.SevenStep = data.subMData[i].SevenStep;
                    Nums += pB_DesignDetail.SevenStep == null ? 0 : pB_DesignDetail.SevenStep;
                    if (data.subMData[i].EightStep < 0)
                    {
                        throw new BusException("第八步不能出现负数");
                    }
                    pB_DesignDetail.EightStep = data.subMData[i].EightStep;
                    Nums += pB_DesignDetail.EightStep == null ? 0 : pB_DesignDetail.EightStep;
                    if (data.subMData[i].NineStep < 0)
                    {
                        throw new BusException("第九步不能出现负数");
                    }
                    pB_DesignDetail.NineStep = data.subMData[i].NineStep;
                    Nums += pB_DesignDetail.NineStep == null ? 0 : pB_DesignDetail.NineStep;
                    if (data.subMData[i].TenStep < 0)
                    {
                        throw new BusException("第十步不能出现负数");
                    }
                    pB_DesignDetail.TenStep = data.subMData[i].TenStep;
                    Nums += pB_DesignDetail.TenStep == null ? 0 : pB_DesignDetail.TenStep;

                    if (Nums != pB_DesignDetail.RealNums)
                    {
                        throw new BusException("步数设计数量与总设计数量不一致");
                    }
                    ListDesignDetail.Add(pB_DesignDetail);
                }
                var intrunt = await ExecuteSqlAsync("DELETE FROM PB_DesignDetail WHERE ParentId in ('" + data.PId + "') and State=0 ");

                await Db.InsertAsync(ListDesignDetail);
                #endregion
            }
            //先删除原有的l关联数据
            //var where = LinqHelper.True<PB_DesignDetail>();
            //if (!data.PId.IsNullOrEmpty())
            //{
            //    var newWhere = DynamicExpressionParser.ParseLambda<PB_DesignDetail, bool>(
            //            ParsingConfig.Default, false, $@"ParentId.Equals(@0)", data.PId);
            //    where = where.And(newWhere);
            //}
            //var DbInfo = Db.GetIQueryable<PB_DesignDetail>();


            #region //2022-03-04 朱柏清 项目执行过程明细

            PB_DesignList pB_DesignList = Db.GetIQueryable<PB_DesignList>().Where(s => s.Id == data.PId).FirstOrDefault();
            string type = Db.GetIQueryable<Base_EnumItem>().Where(u => u.EnumCode.Contains("ProjectProcessType") && u.Name.Contains("设计清单")).FirstOrDefault().Value;
            string bn = Db.GetIQueryable<PB_Buildingnumber>().Where(u => u.Id == pB_DesignList.BuildingNumberID).FirstOrDefault().Buildingnumber;
            PB_ProjectProcess pB_ProjectProcess = new PB_ProjectProcess();

            pB_ProjectProcess.Id = IdHelper.GetId();
            pB_ProjectProcess.ProjectId = pB_DesignList.ProjectId;
            pB_ProjectProcess.ProjectName = pB_DesignList.ProjectName;
            pB_ProjectProcess.ProcessType = type;
            pB_ProjectProcess.BuildingnumberId = pB_DesignList.BuildingNumberID;
            pB_ProjectProcess.BuildingnumberName = bn;
            pB_ProjectProcess.Remarks = "修改";
            pB_ProjectProcess.CreatorId = _operator.UserId;
            pB_ProjectProcess.CreatorRealName = _operator.Property.RealName;
            pB_ProjectProcess.CreateTime = DateTime.Now;
            pB_ProjectProcess.Deleted = false;
            pB_ProjectProcess.OrderId = pB_DesignList.Id;

            await Db.InsertAsync<PB_ProjectProcess>(pB_ProjectProcess);
            #endregion
        }

        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="id">清单ID</param>
        /// <param name="stateType">状态</param>
        /// <returns></returns>
        public async Task ToExamineDataAsync(string id, int stateType)
        {

            //设计清单审核判断是工作流有正在进行的任务
            string sql = "select Level from  Base_OverFlowTask where BillId='" + id + "'";
            var listcount = await Db.GetListBySqlAsync<Base_OverFlowTask>(sql);
            if (listcount.Count > 0)
            {

                if (listcount[0].Level > 0)
                {
                    throw new BusException("钉钉还有正在处理的审批!");
                }
                else
                {
                    string sqldelete = "delete from Base_OverFlowTask WHERE BillId='" + id + "' ";
                    await ExecuteSqlAsync(sqldelete);
                }



            }


            string sqlMain = @"update PB_DesignList set ExamineStatus='" + stateType + "',ToExamineId='" + _operator.UserId + "',ToExamineName='" + _operator?.Property?.RealName + "',ToExamineTime='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where Id='" + id + "'";
            await ExecuteSqlAsync(sqlMain);

            //设计清单审核成功推送消息

            //await Db.ExecuteSqlAsync("INSERT INTO Base_OverFlowTask VALUES ('" + id + "','DesignList',0)");


            //2022-03-04 朱柏清 项目执行过程明细
            PB_DesignList pB_DesignList = Db.GetIQueryable<PB_DesignList>().Where(s => s.Id == id).FirstOrDefault();
            PB_ProjectProcess pB_ProjectProcess = new PB_ProjectProcess
            {
                Id = IdHelper.GetId(),
                ProjectId = pB_DesignList.ProjectId,
                ProjectName = pB_DesignList.ProjectName,
                ProcessType = Db.GetIQueryable<Base_EnumItem>().Where(u => u.EnumCode.Contains("ProjectProcessType") && u.Name.Contains("设计清单")).FirstOrDefault().Value,
                BuildingnumberId = pB_DesignList.BuildingNumberID,
                BuildingnumberName = Db.GetIQueryable<PB_Buildingnumber>().Where(u => u.Id == pB_DesignList.BuildingNumberID).FirstOrDefault().Buildingnumber,
                Remarks = "审核",
                CreatorId = _operator.UserId,
                CreatorRealName = _operator.Property.RealName,
                CreateTime = DateTime.Now,
                OrderId = pB_DesignList.Id,
                Deleted = false,
            };
            await Db.InsertAsync<PB_ProjectProcess>(pB_ProjectProcess);

            //如果是审批通过

            //审批人
            //List<string> ulist = new List<string>();
            ////抄送人
            //List<string> ulistcc = new List<string>();
            ////获取设计清单数据
            //StringBuilder sql = new StringBuilder();
            //sql.AppendLine("SELECT ");
            //sql.AppendLine("Base_OverFlow.Id,");
            //sql.AppendLine("Base_OverFlow.Content,");
            //sql.AppendLine("ifnull( Base_OverFlowTask.LEVEL, 0 ) LEVEL ");
            //sql.AppendLine("FROM ");
            //sql.AppendLine("PB_DesignList");
            //sql.AppendLine("INNER JOIN Base_OverFlowTask ON Base_OverFlowTask.BillId = PB_DesignList.Id");
            //sql.AppendLine("INNER JOIN Base_OverFlow ON Base_OverFlow.BillType = Base_OverFlowTask.BillType");
            //sql.AppendLine("WHERE ");
            //sql.AppendLine("PB_DesignList.Id = '" + id + "'");
            //Util.Helper.DingInputDTO input = new Util.Helper.DingInputDTO();
            //string uids = "";
            //var flowMob = await Db.GetListBySqlAsync<CurrentOverFlowDTO>(sql.ToString());
            //JArray farrMob = JArray.Parse(flowMob[0].Content);
            //JObject _objMob = JObject.Parse(farrMob[flowMob[0].Level].ToString());

            //#region 设计清单审核推送审核人 抄送人
            //JArray usrMob = JArray.Parse(farrMob[0]["Assignees"]["UserId"].ToString());
            //var list = await Db.GetIQueryable<PB_DesignList>().Where(m => m.Id == id).FirstOrDefaultAsync();
            //var ProjectName = await Db.GetIQueryable<PB_Project>().Where(m => m.Id == list.ProjectId).FirstOrDefaultAsync();
            //var Buildingnumber = await Db.GetIQueryable<PB_Buildingnumber>().Where(m => m.Id == list.BuildingNumberID).FirstOrDefaultAsync();
            //input.Str = $"设计清单:{ProjectName.Name}{Buildingnumber.Buildingnumber}请审批" + DateTime.Now.ToString("");
            //string url = "eapp://pages/info/info?billid=" + id + "&title=" + _objMob["StartState"]["Name"] + "&btn=" + _objMob["Action"]["Name"].ToString() + "&id=" + flowMob[0].Id + "";
            //input.MessgUrl = url;
            //input.BillId = id;
            //if (usrMob.Count > 0)
            //{
            //    foreach (var u in usrMob)
            //    {
            //        uids += "'" + u + "',";
            //    }
            //    var emps = await Db.GetListBySqlAsync<Base_User>("SELECT * FROM Base_User WHERE Id IN (" + uids.Substring(0, uids.Length - 1) + ")");
            //    foreach (var e in emps)
            //    {
            //        ulist.Add(e.DingUserId);
            //    }
            //}
            //input.ExecutorIds = ulist;
            //DingHelper.sendMessage(input);
            //获取抄送人
            //string uidscc = "";
            //JArray usrMobCC = JArray.Parse(farrMob[0]["Assignees"]["PersonId"].ToString());
            //Util.Helper.DingInputDTO inputcc = new Util.Helper.DingInputDTO();
            //inputcc.Str = $"设计清单:{ProjectName.Name}{Buildingnumber.Buildingnumber}" + DateTime.Now.ToString("");
            //string urlcc = $"eapp://pages/infoView/infoView?BillId={input.BillId}";
            //inputcc.MessgUrl = urlcc;
            //inputcc.BillId = id;
            //if (usrMobCC.Count > 0)
            //{
            //    foreach (var u in usrMobCC)
            //    {
            //        uidscc += "'" + u + "',";
            //    }
            //    var emps = await Db.GetListBySqlAsync<Base_User>("SELECT * FROM Base_User WHERE Id IN (" + uidscc.Substring(0, uidscc.Length - 1) + ")");
            //    foreach (var e in emps)
            //    {
            //        ulistcc.Add(e.DingUserId);
            //    }

            //    inputcc.ExecutorIds = ulistcc;
            //    DingHelper.sendMessage(inputcc);
            //    #endregion
            //}

        }
        /// <summary>
        /// 清单变更
        /// </summary>
        /// <param name="id">清单ID</param>
        /// <returns></returns>
        [Transactional]
        public async Task UpdateDesignListDataChangeAsync(string id)
        {
            int VersionNumber = 0;
            //先查询清单是否存在版本号
            var qdata = Db.GetIQueryable<PB_DesignListVersion>().Where(x => x.ParentId == id).OrderByDescending(x => x.VersionNumber).FirstOrDefault();
            Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();
            if (qdata == null)
            {
                PB_DesignListVersion pbdata = new PB_DesignListVersion
                {
                    Id = IdHelper.GetId(),
                    ParentId = id,
                    VersionNumber = 1,
                    CreatorId = _operator.UserId,
                    CreatorRealName = bdata.RealName,
                    CreateTime = DateTime.Now,
                    Deleted = false
                };
                await Db.InsertAsync(pbdata);
            }
            else
            {
                VersionNumber = qdata.VersionNumber + 1;
                PB_DesignListVersion pbdata = new PB_DesignListVersion
                {
                    Id = IdHelper.GetId(),
                    ParentId = id,
                    VersionNumber = VersionNumber,
                    CreatorId = _operator.UserId,
                    CreatorRealName = bdata.RealName,
                    CreateTime = DateTime.Now,
                    Deleted = false
                };
                await Db.InsertAsync(pbdata);
            }
            await ExecuteSqlAsync("update PB_DesignList set ExamineStatus=4 where Id='" + id + "'");
            //2022-03-04 朱柏清 项目执行过程明细
            PB_DesignList pB_DesignList = Db.GetIQueryable<PB_DesignList>().Where(s => s.Id == id).FirstOrDefault();
            PB_ProjectProcess pB_ProjectProcess = new PB_ProjectProcess();

            pB_ProjectProcess.Id = IdHelper.GetId();
              pB_ProjectProcess.ProjectId = pB_DesignList.ProjectId;
               pB_ProjectProcess.ProjectName = pB_DesignList.ProjectName;
              pB_ProjectProcess.ProcessType = Db.GetIQueryable<Base_EnumItem>().Where(u => u.EnumCode.Contains("ProjectProcessType") && u.Name.Contains("设计清单")).FirstOrDefault().Value;
               pB_ProjectProcess.BuildingnumberId = pB_DesignList.BuildingNumberID;
               pB_ProjectProcess.BuildingnumberName = Db.GetIQueryable<PB_Buildingnumber>().Where(u => u.Id == pB_DesignList.BuildingNumberID).FirstOrDefault().IsNullOrEmpty()?"": Db.GetIQueryable<PB_Buildingnumber>().Where(u => u.Id == pB_DesignList.BuildingNumberID).FirstOrDefault().Buildingnumber;
                pB_ProjectProcess.Remarks = "变更";
                pB_ProjectProcess.CreatorId = _operator.UserId;
               pB_ProjectProcess.CreatorRealName = _operator.Property.RealName;
                pB_ProjectProcess.CreateTime = DateTime.Now;
               pB_ProjectProcess.OrderId = pB_DesignList.Id;
                pB_ProjectProcess.Deleted = false;
            
            await Db.InsertAsync<PB_ProjectProcess>(pB_ProjectProcess);
        }

        /// <summary>
        /// 获取版本信息
        /// </summary>
        /// <param name="id">清单ID</param>
        /// <returns></returns>
        public PB_DesignListVersion GetDesignListVersionAsync(string id)
        {
            int VersionNumber = 0;
            //先查询清单是否存在版本号
            var qdata = Db.GetIQueryable<PB_DesignListVersion>().Where(x => x.ParentId == id).OrderByDescending(x => x.VersionNumber).FirstOrDefault();
            Base_User bdata = Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefault();
            if (qdata != null)
            {
                VersionNumber = qdata.VersionNumber + 1;
                PB_DesignListVersion pbdata = new PB_DesignListVersion
                {
                    Id = IdHelper.GetId(),
                    ParentId = id,
                    VersionNumber = VersionNumber,
                    CreatorId = _operator.UserId,
                    CreatorRealName = bdata.RealName,
                    CreateTime = DateTime.Now,
                    Deleted = false
                };
                Db.Insert(pbdata);
            }
            qdata = Db.GetIQueryable<PB_DesignListVersion>().Where(x => x.ParentId == id).OrderByDescending(x => x.VersionNumber).FirstOrDefault();
            return qdata;
        }

        /// <summary>
        /// 清单提交审核
        /// </summary>
        /// <param name="Id">清单Id</param>
        /// <returns></returns>
        public async Task UpdateDataStateAsync(string Id)
        {
            await ExecuteSqlAsync("update PB_DesignList set ExamineStatus=1 where Id='" + Id + "'");
        }

        /// <summary>
        /// 获取设计清单明细是成品的物料
        /// </summary>
        /// <param name="designId">设计清单Id</param>
        /// <returns></returns>
        public async Task<List<PB_DesignListDataDTO>> GetDesignDetailPrintListAsync(string designId)
        {
            string sqlMain = @"select a.Id,a.ParentId,a.MaterialId,b.`Code` as MaterialCode,b.`Name` as MaterialName,b.Spec as MaterialSpec,a.RealNums,IFNULL(c.Nums,0) as Nums from PB_DesignDetail as a join PB_Material as b on a.MaterialId=b.Id left join (select DesignId,DesignDetailId,COUNT(*) as Nums from PB_JobBookingQrCode where DesignId='" + designId + "' group by DesignId,DesignDetailId) as c on a.Id=c.DesignDetailId and a.ParentId=c.DesignId where a.ParentId='" + designId + "' and b.IsProduct=1 ";
            var list = await Db.GetDataTableWithSqlAsync(sqlMain);
            List<PB_DesignListDataDTO> listdata = new List<PB_DesignListDataDTO>();
            if (list.Rows.Count > 0)
            {
                foreach (DataRow dr in list.Rows)
                {
                    PB_DesignListDataDTO data = new PB_DesignListDataDTO();
                    data.Id = dr["Id"].ToString();
                    data.ParentId = dr["ParentId"].ToString();
                    data.MaterialId = dr["MaterialId"].ToString();
                    data.MaterialCode = dr["MaterialCode"].ToString();
                    data.MaterialName = dr["MaterialName"].ToString();
                    data.MaterialSpec = dr["MaterialSpec"].ToString();
                    data.RealNums = Convert.ToDouble(dr["RealNums"]);
                    data.Nums = Convert.ToInt32(dr["Nums"]);
                    listdata.Add(data);
                }
            }
            return listdata;
        }

        /// <summary>
        /// 设计清单成品物料打印
        /// </summary>
        /// <param name="input">设计清单id+打印集合</param>
        /// <param name="_mongodbOptions">设计清单Id</param>
        /// <param name="_redisOptions">设计清单Id</param>
        /// <returns></returns>
        [Transactional]
        public async Task PrintDesignDetailListAsync(MaterialNumDTO input, MongoDBOptions _mongodbOptions, RedisOptions _redisOptions)
        {
            Expression<Func<PB_DesignDetail, PB_Material, Base_Department, PB_MaterialType, PB_DesignDetailPrintDTO>> select = (a, b, c, d) => new PB_DesignDetailPrintDTO
            {
                Id = a.Id,
                ParentId = a.ParentId,
                MaterialId = a.MaterialId,
                MaterialCode = b.Code,
                MaterialName = b.Name,
                MaterialSpec = b.Spec,
                MaterialType = d.Name,
                DeptId = b.DeptId,
                DeptName = c.Name,
                IsProduct = b.IsProduct,
                IsNumber = b.IsNumber
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_DesignDetail>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Department>() on b.DeptId equals c.Id into bc
                    from c in bc.DefaultIfEmpty()
                    join d in Db.GetIQueryable<PB_MaterialType>() on b.MaterialTypeId equals d.Id into bd
                    from d in bd.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d);
            q = q.Where(x => x.ParentId == input.DesignId && x.IsProduct == true && input.liststr.Contains(x.Id));
            var res = await q.ToListAsync();
            if (res.Count > 0)
            {
                List<PrintQueue> listdata = new List<PrintQueue>();
                List<PB_JobBookingQrCode> listcode = new List<PB_JobBookingQrCode>();
                List<PB_JobBookingDetailed> pbdetailed = new List<PB_JobBookingDetailed>();
                //实例化Redis操作类
                _redisOptions.DbChannel = (int)Redis_Type.redis6;
                RedisSetHelper redis = new RedisSetHelper(_redisOptions);
                Base_User bdata = await Db.GetIQueryable<Base_User>().Where(x => x.Id == _operator.UserId).FirstOrDefaultAsync();

                foreach (var item in res)
                {
                    if (item.IsNumber == true)
                    {
                        int i = 0;
                        do
                        {
                            PrintQueue pq = new PrintQueue();
                            PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();
                            string jobcodeId = IdHelper.GetId();   //成品档案表ID
                            pq.Id = IdHelper.GetId();
                            pq.Name = item.MaterialName;
                            pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                            pq.Dept = item.DeptName;
                            if (RedisSetHelper.Exists("QualityTestingNumber"))
                            {
                                string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                                if (redis.GetString("QualityTestingTime") == thedate)
                                {
                                    redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                    pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                }
                                else
                                {
                                    redis.SetString("QualityTestingTime", thedate);
                                    redis.SetString("QualityTestingNumber", "1");
                                    pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                    jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                }
                            }
                            else
                            {
                                redis.SetString("QualityTestingNumber", "0");
                            }
                            pq.QrCode = h_FinishedProduct + "," + jobcodeId;
                            pq.TypeName = item.MaterialType;
                            pq.Type = Skill_Type.Design.ToString();
                            pq.Status = "0";
                            pq.Printer = input.PrinterId;
                            listdata.Add(pq);
                            jkcode.Id = jobcodeId;
                            jkcode.DesignId = item.ParentId;
                            jkcode.DesignDetailId = item.Id;
                            jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                            jkcode.MaterialId = item.MaterialId;
                            jkcode.MaterialName = item.MaterialName;
                            jkcode.OldOrNew = 1;
                            listcode.Add(jkcode);
                            i++;
                        } while (i < item.RealNums);

                        //操作明细插入mongo
                        PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                        pbdata.Id = IdHelper.GetId();
                        pbdata.No = item.Id;
                        pbdata.Nums = item.RealNums;
                        pbdata.DeptId = item.DeptId;
                        pbdata.OperationUserId = _operator.UserId;
                        pbdata.OperationUserName = bdata.RealName;
                        pbdata.OperationTime = DateTime.Now;
                        pbdata.DesignId = item.ParentId;
                        pbdata.DesignDetailId = item.Id;
                        pbdata.Type = 3;
                        pbdata.OldOrNew = 1;
                        pbdata.PrinterId = input.PrinterId;
                        pbdetailed.Add(pbdata);
                    }
                    else
                    {
                        PrintQueue pq = new PrintQueue();
                        PB_JobBookingQrCode jkcode = new PB_JobBookingQrCode();
                        string jobcodeId = IdHelper.GetId();   //成品档案表ID
                        pq.Id = IdHelper.GetId();
                        pq.Name = item.MaterialName;
                        pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                        pq.Dept = item.DeptName;
                        if (RedisSetHelper.Exists("QualityTestingNumber"))
                        {
                            string thedate = DateTime.Now.ToString("yyyy-MM-dd");
                            if (redis.GetString("QualityTestingTime") == thedate)
                            {
                                redis.SetString("QualityTestingNumber", (Convert.ToInt32(redis.GetString("QualityTestingNumber")) + 1).ToString());
                                pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            }
                            else
                            {
                                redis.SetString("QualityTestingTime", thedate);
                                redis.SetString("QualityTestingNumber", "1");
                                pq.No = jobcodeId + "," + redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                                jkcode.SerialNumber = redis.GetString("QualityTestingNumber").PadLeft(5, '0');
                            }
                        }
                        else
                        {
                            redis.SetString("QualityTestingNumber", "0");
                        }
                        pq.QrCode = h_FinishedProduct + "," + jobcodeId;
                        pq.TypeName = item.MaterialType;
                        pq.Type = Skill_Type.Design.ToString();
                        pq.Status = "0";
                        pq.Printer = input.PrinterId;
                        listdata.Add(pq);
                        jkcode.Id = jobcodeId;
                        jkcode.DesignId = item.ParentId;
                        jkcode.DesignDetailId = item.Id;
                        jkcode.QrCode = h_FinishedProduct + "," + jobcodeId;
                        jkcode.MaterialId = item.MaterialId;
                        jkcode.MaterialName = item.MaterialName;
                        jkcode.OldOrNew = 1;
                        listcode.Add(jkcode);

                        //操作明细插入mongo
                        PB_JobBookingDetailed pbdata = new PB_JobBookingDetailed();
                        pbdata.Id = IdHelper.GetId();
                        pbdata.No = item.Id;
                        pbdata.Nums = item.RealNums;
                        pbdata.DeptId = item.DeptId;
                        pbdata.OperationUserId = _operator.UserId;
                        pbdata.OperationUserName = bdata.RealName;
                        pbdata.OperationTime = DateTime.Now;
                        pbdata.DesignId = item.ParentId;
                        pbdata.DesignDetailId = item.Id;
                        pbdata.Type = 3;
                        pbdata.OldOrNew = 1;
                        pbdata.PrinterId = input.PrinterId;
                        pbdetailed.Add(pbdata);
                    }
                }
                MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                listdata.GroupBy(x => new { x.Id, x.No, x.Name, x.TypeName, x.Date, x.Dept, x.QrCode, x.Type, x.Status, x.Printer }).Select(x => new
                {
                    Id = x.Key.Id,
                    No = x.Key.No,
                    Name = x.Key.Name,
                    TypeName = x.Key.TypeName,
                    Date = x.Key.Date,
                    Dept = x.Key.Dept,
                    QrCode = x.Key.QrCode,
                    Type = x.Key.Type,
                    Status = x.Key.Status,
                    Printer = x.Key.Printer
                }).ToList();

                //插入mongo队列
                await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
                //插入mongo报工操作明细
                await mongo.InsertManyAsync<PB_JobBookingDetailed>(JobBookingOperation, pbdetailed);

                //统计完插入报工明细表二维码信息
                await Db.InsertAsync(listcode);
            }
            else
            {
                throw new BusException("暂无数据");
            }

        }

        /// <summary>
        /// 设计清单成品物料明细
        /// </summary>
        /// <param name="designdetailId">设计清单明细Id</param>
        /// <returns></returns>
        public async Task<List<PB_JobBookingQrCodeDTO>> GetDesignDetailJobBookingQrCodeAsync(string designdetailId)
        {
            Expression<Func<PB_JobBookingQrCode, PB_Material, PB_MaterialType, Base_Department, PB_JobBookingQrCodeDTO>> select = (a, b, c, d) => new PB_JobBookingQrCodeDTO
            {
                MaterialCode = b.Code,
                MaterialTypeName = c.Name,
                DeptId = b.DeptId,
                DeptName = d.Name
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_JobBookingQrCode>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_MaterialType>() on b.MaterialTypeId equals c.Id into bc
                    from c in bc.DefaultIfEmpty()
                    join d in Db.GetIQueryable<Base_Department>() on b.DeptId equals d.Id into bd
                    from d in bd.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d);
            q = q.Where(x => x.DesignDetailId == designdetailId);
            var res = await q.ToListAsync();
            if (res.Count > 0)
            {
                return res;
            }
            else
            {
                throw new BusException("暂无数据");
            }
        }

        /// <summary>
        /// 设计清单成品物料补打
        /// </summary>
        /// <param name="data"></param>
        /// <param name="_mongodbOptions">设计清单Id</param>
        /// <returns></returns>
        public async Task PrintDesignDetailJobBookingQrCodeAsync(PB_DesignDetailPrintDataDTO data, MongoDBOptions _mongodbOptions)
        {
            Expression<Func<PB_JobBookingQrCode, PB_Material, PB_MaterialType, Base_Department, PB_JobBookingQrCodeDTO>> select = (a, b, c, d) => new PB_JobBookingQrCodeDTO
            {
                MaterialCode = b.Code,
                MaterialTypeName = c.Name,
                DeptId = b.DeptId,
                DeptName = d.Name,
                IsStandard=b.IsStandard,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_JobBookingQrCode>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_MaterialType>() on b.MaterialTypeId equals c.Id into bc
                    from c in bc.DefaultIfEmpty()
                    join d in Db.GetIQueryable<Base_Department>() on b.DeptId equals d.Id into bd
                    from d in bd.DefaultIfEmpty()
                    select @select.Invoke(a, b, c, d);
            var qdata = await q.Where(x => x.DesignDetailId == data.designdetailId && data.nums.Contains(x.Id)).ToListAsync();
            if (qdata.Count > 0)
            {
                List<PrintQueue> listdata = new List<PrintQueue>();
                foreach (var item in qdata)
                {
                    PrintQueue pq = new PrintQueue();
                    pq.Id = IdHelper.GetId();
                    pq.No = item.Id + "," + item.SerialNumber;
                    pq.Name = item.MaterialName;
                    pq.TypeName = item.MaterialTypeName;
                    pq.Date = DateTime.Now.ToString("yyyy-MM-dd");
                    pq.Dept = item.DeptName;
                    pq.QrCode = item.QrCode;
                    pq.Type = Skill_Type.Design.ToString();
                    pq.Status = "0";
                    pq.Printer = data.PrinterId;
                    pq.ProjectName = "";
                    pq.BuildingNumberName = "";
                    pq.IsStandard = item.IsStandard == false ? 0 : 1;
                    listdata.Add(pq);
                }
                MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                //插入mongo队列
                await mongo.InsertManyAsync<PrintQueue>(PrintQueueCollection, listdata);
            }
            else
            {
                throw new BusException("请选择后打印");
            }
        }

        public async Task<PageResult<PB_DesignListBulidingDTO>> GetDataListItemAsync(PageInput<ConditionDTO> input)
        {

            //var q = GetIQueryable();
            var where = LinqHelper.True<PB_DesignListBulidingDTO>();
            var search = input.Search;


            Expression<Func<PB_DesignList, PB_Buildingnumber, PB_Project, PB_DesignListBulidingDTO>> select = (e, f, g) => new PB_DesignListBulidingDTO
            {

                BuildingnumberName = f.Buildingnumber, //楼号
                ProjectName = e.ProjectName,//项目
                ProjectNames = g.Name,

            };
            select = select.BuildExtendSelectExpre();
            var q = from e in GetIQueryable().AsExpandable()
                    join f in Db.GetIQueryable<PB_Buildingnumber>() on e.BuildingNumberID equals f.Id into ef
                    from f in ef.DefaultIfEmpty()
                    join g in Db.GetIQueryable<PB_Project>() on e.ProjectId equals g.Id into eg
                    from g in eg.DefaultIfEmpty()
                    select @select.Invoke(e, f, g);
            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_DesignListBulidingDTO, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }
            if (!search.ProjectName.IsNullOrEmpty())
            {
                where = where.And(m => m.ProjectNames.Contains(search.ProjectName));
            }
            where = where.And(d => _operator.Property.DeptIds.Contains(d.DeptId));
            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<List<ListSelectionDto>> GetListSelection(SSS data)
        {
            Expression<Func<PB_DesignList, PB_Buildingnumber, PB_DesignListDto>> select = (a, b) => new PB_DesignListDto
            {

            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_Buildingnumber>() on a.BuildingNumberID equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    select @select.Invoke(a, b);
            List<ListSelectionDto> listdata = new List<ListSelectionDto>();
            var qdata = await q.Where(x => x.ProjectId == data.proid && x.BuildingNumberID == data.buid).ToListAsync();
            foreach (var item in qdata)
            {
                Expression<Func<PB_DesignDetail, PB_Material, PB_MaterialType, PB_DesignDetailDTO>> select2 = (a, b, c) => new PB_DesignDetailDTO
                {
                    MaterialID = b.Id,//物料编号
                    MaterialName = b.Name,//物料名称
                    MaterialTypeId = c.Name,//类型名称
                    MaterialCode = b.Code,//物料编号
                    Weight = b.Weight,//理论重量


                };
                select2 = select2.BuildExtendSelectExpre();
                var q2 = from a in Db.GetIQueryable<PB_DesignDetail>().AsExpandable()
                         join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                         from b in ab.DefaultIfEmpty()
                         join c in Db.GetIQueryable<PB_MaterialType>() on b.MaterialTypeId equals c.Id into ac
                         from c in ac.DefaultIfEmpty()
                         select select2.Invoke(a, b, c);
                var res = await q2.Where(x => x.ParentId == item.Id).ToListAsync();
                ListSelectionDto pblist = new ListSelectionDto();
                pblist.Id = item.Id;
                pblist.Code = item.Code;
                pblist.ContractNo = item.ContractNo;
                pblist.ProjectId = item.ProjectId;
                pblist.Name = item.Name;
                pblist.ProjectName = item.Name;
                pblist.StandsNums = item.StandsNums;
                pblist.ProjectAddress = item.ProjectAddress;
                pblist.LiftingMode = item.LiftingMode;
                pblist.Salesman = item.Salesman;
                pblist.SubData = res;
                listdata.Add(pblist);
            }
            if (listdata.Count > 0)
            {
                return listdata;
            }
            else
            {
                throw new BusException("暂无数据");
            }
        }

        public async Task UpdateData(List<PB_DesignDetail> data)
        {
            await Db.UpdateAsync(data);
        }

        public async Task<AjaxResult> GetallCount(string ProjectId, string Buid, int Type)
        {
            Boolean SUS = false;
            var datasubMDatacount = Db.GetListBySqlAsync<PB_DesignList>(@" select * from PB_DesignList WHERE ProjectId='" + ProjectId + "'  and BuildingNumberID='" + Buid + "' and Type='" + Type + "'  ").Result;
            if (datasubMDatacount.Count > 0)
            {
                AjaxResult res = new AjaxResult
                {
                    Success = true,
                    Msg = "true！"
                };

                return res;
            }
            else
            {
                AjaxResult res = new AjaxResult
                {
                    Success = false,
                    Msg = "false！"
                };
                return res;
            }
        }

        public async Task<PB_DesignListPrint> GetDataListPrint(string ParentId)
        {
            PB_DesignListPrint ListData = new PB_DesignListPrint();
            Expression<Func<PB_DesignList, PB_Project, PB_Buildingnumber, PB_DesignListPrint>> select = (a, b, c) => new PB_DesignListPrint
            {
                ProjectName = b.Name,
                BulidNo = c.Buildingnumber,
            };

            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_DesignList>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Project>() on a.ProjectId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Buildingnumber>() on a.BuildingNumberID equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            q = q.Where(x => x.Id == ParentId);
            var qbdata = await q.FirstOrDefaultAsync();
            ListData = qbdata;
            Expression<Func<PB_DesignDetail, PB_Material, Base_UnitItems, PB_DesignDetailDTO>> selects = (a, b, c) => new PB_DesignDetailDTO
            {
                MaterialCode = b.Code,
                MaterialName = b.Name,
                UnitmName = c.Name,
                MaterSpec = b.Spec,

            };

            selects = selects.BuildExtendSelectExpre();
            var k = from a in Db.GetIQueryable<PB_DesignDetail>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_UnitItems>() on b.storageId equals c.Id into bc
                    from c in bc.DefaultIfEmpty()

                    select @selects.Invoke(a, b, c);
            k = k.Where(x => x.ParentId == ParentId);
            k = k.OrderBy(m=>m.Slot);
            var res = await k.ToListAsync();
            ListData.SubDate = res;

            if (res.Count > 0)
            {
                return ListData;
            }
            else
            {
                throw new BusException("暂无数据");
            }

        }

        /// <summary>
        /// 获取设计清单类型
        /// </summary>
        /// <returns></returns>
        public async Task<List<PB_DesignListType>> GetDesignListTypeListAsync()
        {
            List<PB_DesignListType> listdata = await Db.GetIQueryable<PB_DesignListType>().ToListAsync();
            return listdata;
        }

        /// <summary>
        /// 传入设计清单id推送钉钉消息
        /// </summary>
        /// <param name="DesigId">补加单</param>
        /// <returns></returns>
        public async Task GetOverFlowMessage(string DesigId)
        {
            string SqlSelecft = "Select * from  Base_OverFlowTask where BillId='" + DesigId + "'";
            //var Res =await Db.GetListBySqlAsync<Base_OverFlowBill>(SqlSelecft);

            //if (Res.Count>0) {
            //    throw new BusException("钉钉有未审批的单据,禁止导入");
            //}
            //插入工作任务数据
            string sql = "INSERT INTO Base_OverFlowTask VALUES ('" + DesigId + "','InsertDesignList',0)";
            await Db.ExecuteSqlAsync(sql);
            //审批人
            List<string> ulist = new List<string>();
            //抄送人
            List<string> ulistcc = new List<string>();
            //获取设计清单数据
            StringBuilder SqlDesignlist = new StringBuilder();
            SqlDesignlist.AppendLine("SELECT ");
            SqlDesignlist.AppendLine("Base_OverFlow.Id,");
            SqlDesignlist.AppendLine("Base_OverFlow.Content,");
            SqlDesignlist.AppendLine("ifnull( Base_OverFlowTask.LEVEL, 0 ) LEVEL ");
            SqlDesignlist.AppendLine("FROM ");
            SqlDesignlist.AppendLine("PB_DesignList");
            SqlDesignlist.AppendLine("INNER JOIN Base_OverFlowTask ON Base_OverFlowTask.BillId = PB_DesignList.Id");
            SqlDesignlist.AppendLine("INNER JOIN Base_OverFlow ON Base_OverFlow.BillType = Base_OverFlowTask.BillType");
            SqlDesignlist.AppendLine("WHERE ");
            SqlDesignlist.AppendLine("PB_DesignList.Id = '" + DesigId + "'");
            Util.Helper.DingInputDTO input = new Util.Helper.DingInputDTO();
            string uids = "";
            var flowMob = await Db.GetListBySqlAsync<CurrentOverFlowDTO>(SqlDesignlist.ToString());
            JArray farrMob = JArray.Parse(flowMob[0].Content);
            JObject _objMob = JObject.Parse(farrMob[flowMob[0].Level].ToString());

            #region 设计清单审核推送审核人 抄送人
            JArray usrMob = JArray.Parse(farrMob[0]["Assignees"]["UserId"].ToString());
            var list = await Db.GetIQueryable<PB_DesignList>().Where(m => m.Id == DesigId).FirstOrDefaultAsync();
            var ProjectName = await Db.GetIQueryable<PB_Project>().Where(m => m.Id == list.ProjectId).FirstOrDefaultAsync();
            var Buildingnumber = await Db.GetIQueryable<PB_Buildingnumber>().Where(m => m.Id == list.BuildingNumberID).FirstOrDefaultAsync();
            input.Str = $"设计清单补加单:{ProjectName.Name}{Buildingnumber.Buildingnumber}请审批" + DateTime.Now.ToString("");
            string url = "eapp://pages/info/info?billid=" + DesigId + "&title=" + _objMob["StartState"]["Name"] + "&btn=" + _objMob["Action"]["Name"].ToString() + "&id=" + flowMob[0].Id + "";
            input.MessgUrl = url;
            input.BillId = DesigId;
            if (usrMob.Count > 0)
            {
                foreach (var u in usrMob)
                {
                    uids += "'" + u + "',";
                }
                var emps = await Db.GetListBySqlAsync<Base_User>("SELECT * FROM Base_User WHERE Id IN (" + uids.Substring(0, uids.Length - 1) + ")");
                foreach (var e in emps)
                {
                    ulist.Add(e.DingUserId);
                }
            }
            input.ExecutorIds = ulist;
            DingHelper.sendMessage(input);
            //获取抄送人
            string uidscc = "";
            JArray usrMobCC = JArray.Parse(farrMob[0]["Assignees"]["PersonId"].ToString());
            Util.Helper.DingInputDTO inputcc = new Util.Helper.DingInputDTO();
            inputcc.Str = $"设计清单补加单:{ProjectName.Name}{Buildingnumber.Buildingnumber}" + DateTime.Now.ToString("");
            string BliiType = "InsertDesignList";
            string urlcc = $"eapp://pages/infoView/infoView?BillId={DesigId}&UserType=1&BillType={BliiType}&Type=1";
            inputcc.MessgUrl = urlcc;
            inputcc.BillId = DesigId;
            if (usrMobCC.Count > 0)
            {
                foreach (var u in usrMobCC)
                {
                    uidscc += "'" + u + "',";
                }
                var emps = await Db.GetListBySqlAsync<Base_User>("SELECT * FROM Base_User WHERE Id IN (" + uidscc.Substring(0, uidscc.Length - 1) + ")");
                foreach (var e in emps)
                {
                    ulistcc.Add(e.DingUserId);
                }

                inputcc.ExecutorIds = ulistcc;
                DingHelper.sendMessage(inputcc);
                #endregion
            }

            #endregion
            #region 私有成员
            #endregion
        }

        public async Task GetOverFlowAdd(string DesigId)
        {
            string sql = "INSERT INTO Base_OverFlowTask VALUES ('" + DesigId + "','DesignList',0)";
            await Db.ExecuteSqlAsync(sql);
            //审批人
            List<string> ulist = new List<string>();
            //抄送人
            List<string> ulistcc = new List<string>();
            //获取设计清单数据
            StringBuilder SqlDesignlist = new StringBuilder();
            SqlDesignlist.AppendLine("SELECT ");
            SqlDesignlist.AppendLine("Base_OverFlow.Id,");
            SqlDesignlist.AppendLine("Base_OverFlow.Content,");
            SqlDesignlist.AppendLine("ifnull( Base_OverFlowTask.LEVEL, 0 ) LEVEL ");
            SqlDesignlist.AppendLine("FROM ");
            SqlDesignlist.AppendLine("PB_DesignList");
            SqlDesignlist.AppendLine("INNER JOIN Base_OverFlowTask ON Base_OverFlowTask.BillId = PB_DesignList.Id");
            SqlDesignlist.AppendLine("INNER JOIN Base_OverFlow ON Base_OverFlow.BillType = Base_OverFlowTask.BillType");
            SqlDesignlist.AppendLine("WHERE ");
            SqlDesignlist.AppendLine("PB_DesignList.Id = '" + DesigId + "'");
            Util.Helper.DingInputDTO input = new Util.Helper.DingInputDTO();
            string uids = "";
            var flowMob = await Db.GetListBySqlAsync<CurrentOverFlowDTO>(SqlDesignlist.ToString());
            JArray farrMob = JArray.Parse(flowMob[0].Content);
            JObject _objMob = JObject.Parse(farrMob[flowMob[0].Level].ToString());

            #region 设计清单审核推送审核人 抄送人
            JArray usrMob = JArray.Parse(farrMob[0]["Assignees"]["UserId"].ToString());
            var list = await Db.GetIQueryable<PB_DesignList>().Where(m => m.Id == DesigId).FirstOrDefaultAsync();
            var ProjectName = await Db.GetIQueryable<PB_Project>().Where(m => m.Id == list.ProjectId).FirstOrDefaultAsync();
            var Buildingnumber = await Db.GetIQueryable<PB_Buildingnumber>().Where(m => m.Id == list.BuildingNumberID).FirstOrDefaultAsync();
            input.Str = $"设计清单:{ProjectName.Name}{Buildingnumber.Buildingnumber}请审批" + DateTime.Now.ToString("");
            string url = "eapp://pages/info/info?billid=" + DesigId + "&title=" + _objMob["StartState"]["Name"] + "&btn=" + _objMob["Action"]["Name"].ToString() + "&id=" + flowMob[0].Id + "";
            input.MessgUrl = url;
            input.BillId = DesigId;
            if (usrMob.Count > 0)
            {
                foreach (var u in usrMob)
                {
                    uids += "'" + u + "',";
                }
                var emps = await Db.GetListBySqlAsync<Base_User>("SELECT * FROM Base_User WHERE Id IN (" + uids.Substring(0, uids.Length - 1) + ")");
                foreach (var e in emps)
                {
                    ulist.Add(e.DingUserId);
                }
            }
            input.ExecutorIds = ulist;
            DingHelper.sendMessage(input);
            //获取抄送人
            string uidscc = "";
            JArray usrMobCC = JArray.Parse(farrMob[0]["Assignees"]["PersonId"].ToString());
            Util.Helper.DingInputDTO inputcc = new Util.Helper.DingInputDTO();
            inputcc.Str = $"设计清单:{ProjectName.Name}{Buildingnumber.Buildingnumber}" + DateTime.Now.ToString("");
            string BliiType = "DesignList";
            string urlcc = $"eapp://pages/infoView/infoView?BillId={DesigId}&UserType=1&BillType={BliiType}&Type=0";
            inputcc.MessgUrl = urlcc;
            inputcc.BillId = DesigId;
            if (usrMobCC.Count > 0)
            {
                foreach (var u in usrMobCC)
                {
                    uidscc += "'" + u + "',";
                }
                var emps = await Db.GetListBySqlAsync<Base_User>("SELECT * FROM Base_User WHERE Id IN (" + uidscc.Substring(0, uidscc.Length - 1) + ")");
                foreach (var e in emps)
                {
                    ulistcc.Add(e.DingUserId);
                }

                inputcc.ExecutorIds = ulistcc;
                DingHelper.sendMessage(inputcc);
                #endregion
            }
        }

        public async Task updatastate(string DesigId)
        {
            string sql = "Update PB_DesignList set  ExamineStatus=4 where Id='" + DesigId + "'";
            await Db.ExecuteSqlAsync(sql);

        }
        /// <summary>
        /// PC 导入设计清单变更单推送钉钉审批
        /// </summary>
        /// <param name="DesigId"></param>
        /// <returns></returns>
        public async Task PushChangMessage(string DesigId)
        {
            string SqlSelecft = "Select * from  Base_OverFlowTask where BillId='" + DesigId + "'";
            //var Res = await Db.GetListBySqlAsync<Base_OverFlowBill>(SqlSelecft);

            //if (Res.Count > 0)
            //{
            //    throw new BusException("钉钉有未审批的单据,禁止导入");
            //}
            //插入工作任务数据
            string sql = "INSERT INTO Base_OverFlowTask VALUES ('" + DesigId + "','ChangeDesignList',0)";
            await Db.ExecuteSqlAsync(sql);
            //审批人
            List<string> ulist = new List<string>();
            //抄送人
            List<string> ulistcc = new List<string>();
            //获取设计清单数据
            StringBuilder SqlDesignlist = new StringBuilder();
            SqlDesignlist.AppendLine("SELECT ");
            SqlDesignlist.AppendLine("Base_OverFlow.Id,");
            SqlDesignlist.AppendLine("Base_OverFlow.Content,");
            SqlDesignlist.AppendLine("ifnull( Base_OverFlowTask.LEVEL, 0 ) LEVEL ");
            SqlDesignlist.AppendLine("FROM ");
            SqlDesignlist.AppendLine("PB_DesignList");
            SqlDesignlist.AppendLine("INNER JOIN Base_OverFlowTask ON Base_OverFlowTask.BillId = PB_DesignList.Id");
            SqlDesignlist.AppendLine("INNER JOIN Base_OverFlow ON Base_OverFlow.BillType = Base_OverFlowTask.BillType");
            SqlDesignlist.AppendLine("WHERE ");
            SqlDesignlist.AppendLine("PB_DesignList.Id = '" + DesigId + "'");
            Util.Helper.DingInputDTO input = new Util.Helper.DingInputDTO();
            string uids = "";
            var flowMob = await Db.GetListBySqlAsync<CurrentOverFlowDTO>(SqlDesignlist.ToString());
            JArray farrMob = JArray.Parse(flowMob[0].Content);
            JObject _objMob = JObject.Parse(farrMob[flowMob[0].Level].ToString());

            #region 设计清单审核推送审核人 抄送人
            JArray usrMob = JArray.Parse(farrMob[0]["Assignees"]["UserId"].ToString());
            var list = await Db.GetIQueryable<PB_DesignList>().Where(m => m.Id == DesigId).FirstOrDefaultAsync();
            var ProjectName = await Db.GetIQueryable<PB_Project>().Where(m => m.Id == list.ProjectId).FirstOrDefaultAsync();
            var Buildingnumber = await Db.GetIQueryable<PB_Buildingnumber>().Where(m => m.Id == list.BuildingNumberID).FirstOrDefaultAsync();
            input.Str = $"设计清单变更单:{ProjectName.Name}{Buildingnumber.Buildingnumber}请审批" + DateTime.Now.ToString("");
            string url = "eapp://pages/info/info?billid=" + DesigId + "&title=" + _objMob["StartState"]["Name"] + "&btn=" + _objMob["Action"]["Name"].ToString() + "&id=" + flowMob[0].Id + "";
            input.MessgUrl = url;
            input.BillId = DesigId;
            if (usrMob.Count > 0)
            {
                foreach (var u in usrMob)
                {
                    uids += "'" + u + "',";
                }
                var emps = await Db.GetListBySqlAsync<Base_User>("SELECT * FROM Base_User WHERE Id IN (" + uids.Substring(0, uids.Length - 1) + ")");
                foreach (var e in emps)
                {
                    ulist.Add(e.DingUserId);
                }
            }
            input.ExecutorIds = ulist;
            DingHelper.sendMessage(input);
            //获取抄送人
            string uidscc = "";
            JArray usrMobCC = JArray.Parse(farrMob[0]["Assignees"]["PersonId"].ToString());
            Util.Helper.DingInputDTO inputcc = new Util.Helper.DingInputDTO();
            inputcc.Str = $"设计清单变更单:{ProjectName.Name}{Buildingnumber.Buildingnumber}" + DateTime.Now.ToString("");
            string BliiType = "ChangeDesignList";
            string urlcc = $"eapp://pages/infoView/infoView?BillId={DesigId}&UserType=1&BillType={BliiType}&Type=1";
            inputcc.MessgUrl = urlcc;
            inputcc.BillId = DesigId;
            if (usrMobCC.Count > 0)
            {
                foreach (var u in usrMobCC)
                {
                    uidscc += "'" + u + "',";
                }
                var emps = await Db.GetListBySqlAsync<Base_User>("SELECT * FROM Base_User WHERE Id IN (" + uidscc.Substring(0, uidscc.Length - 1) + ")");
                foreach (var e in emps)
                {
                    ulistcc.Add(e.DingUserId);
                }

                inputcc.ExecutorIds = ulistcc;
                DingHelper.sendMessage(inputcc);
                #endregion
            }

        }

        public async Task<string> GetFileAddress(string DesigId, string Type)
        {
            string FileAddress = string.Empty;
            if (Type == "0")
            {
                var FIle = await Db.GetIQueryable<PB_DesignListFile>().Where(m => m.DesignId == DesigId && m.Type == 0).FirstOrDefaultAsync();
                if (FIle == null)
                {
                    FileAddress = "未上传附件";
                }
                else
                {
                    FileAddress = FIle.DetailedFile;
                }
            }
            else if (Type == "1")
            {
                var FIle = await Db.GetIQueryable<PB_DesignListFile>().Where(m => m.DesignId == DesigId && m.Type == 1).FirstOrDefaultAsync();
                if (FIle == null)
                {
                    FileAddress = "未上传附件";
                }
                else
                {
                    FileAddress = FIle.DetailedFile;
                }
            }
            return FileAddress;
        }

        public async Task MaintenanceSteps(PB_designDetaliList data,string Parentid)
        {
            
         
            List<PB_DesignDetail> updateDetailList = new List<PB_DesignDetail>();
            foreach (var item in data.subdata) {
                double? nums = 0;
                PB_DesignDetail pB_DesignDetail = new PB_DesignDetail();
                pB_DesignDetail.Id = item.SubId;
                pB_DesignDetail.ParentId = Parentid;
                pB_DesignDetail.MaterialId = item.Id;
                pB_DesignDetail.Nums = item.Nums;
                pB_DesignDetail.RealNums = item.RealNums;
                pB_DesignDetail.ShipmentNums = item.ShipmentNums;
                pB_DesignDetail.Remarks = item.Remarks;
                pB_DesignDetail.CreateTime = DateTime.Now;
                pB_DesignDetail.VersionNumber = 0;
                pB_DesignDetail.CreatorId =_operator.UserId;
                pB_DesignDetail.Deleted = item.Deleted;
                pB_DesignDetail.Weight = item.Weight;
                pB_DesignDetail.VersionNumber = item.VersionNumber;
                pB_DesignDetail.State = item.State;
                pB_DesignDetail.ReplaceId = item.ReplaceId;
                pB_DesignDetail.Slot = item.Slot;
                nums += pB_DesignDetail.OneStep = item.OneStep == null ? 0 : item.OneStep;
                nums += pB_DesignDetail.TwoStep = item.TwoStep == null ? 0 : item.TwoStep;
                nums += pB_DesignDetail.ThreeStep = item.ThreeStep == null ? 0 : item.ThreeStep;
                nums += pB_DesignDetail.FourStep = item.FourStep == null ? 0 : item.FourStep;
                nums += pB_DesignDetail.FiveStep = item.FiveStep == null ? 0 : item.FiveStep;
                nums += pB_DesignDetail.SixStep = item.SixStep == null ? 0 : item.SixStep;
                nums += pB_DesignDetail.SevenStep = item.SevenStep == null ? 0 : item.SevenStep;
                nums += pB_DesignDetail.EightStep = item.EightStep == null ? 0 : item.EightStep;
                nums += pB_DesignDetail.NineStep = item.NineStep == null ? 0 : item.NineStep;
                nums += pB_DesignDetail.TenStep = item.TenStep == null ? 0 : item.TenStep;
                nums += pB_DesignDetail.ElevenStep = item.ElevenStep == null ? 0 : item.ElevenStep;
                nums += pB_DesignDetail.TwelveStep = item.TwelveStep == null ? 0 : item.TwelveStep;
                nums += pB_DesignDetail.ThirteenStep = item.ThirteenStep == null ? 0 : item.ThirteenStep;
                nums += pB_DesignDetail.FourteenStep = item.FourteenStep == null ? 0 : item.FourteenStep;
                nums += pB_DesignDetail.FifteenStep = item.FifteenStep == null ? 0 : item.FifteenStep;
                pB_DesignDetail.OneStepReady = item.OneStepReady == null ? 0 : item.OneStepReady;
                pB_DesignDetail.TwoStepReady = item.TwoStepReady == null ? 0 : item.TwoStepReady;
                pB_DesignDetail.ThreeStepReady = item.ThreeStepReady == null ? 0 : item.ThreeStepReady;
                pB_DesignDetail.FourStepReady = item.FourStepReady == null ? 0 : item.FourStepReady;
                pB_DesignDetail.FiveStepReady = item.FiveStepReady == null ? 0 : item.FiveStepReady;
                pB_DesignDetail.SixStepReady = item.SixStepReady == null ? 0 : item.SixStepReady;
                pB_DesignDetail.SevenStepReady = item.SevenStepReady == null ? 0 : item.SevenStepReady;
                pB_DesignDetail.EightStepReady = item.EightStepReady == null ? 0 : item.EightStepReady;
                pB_DesignDetail.NineStepReady = item.NineStepReady == null ? 0 : item.NineStepReady;
                pB_DesignDetail.TenStepReady = item.TenStepReady == null ? 0 : item.TenStepReady;
                pB_DesignDetail.ElevenStepReady = item.ElevenStepReady == null ? 0 : item.ElevenStepReady;
                pB_DesignDetail.TwelveStepReady = item.TwelveStepReady == null ? 0 : item.TwelveStepReady;
                pB_DesignDetail.ThirteenStepReady = item.ThirteenStepReady == null ? 0 : item.ThirteenStepReady;
                pB_DesignDetail.FourteenStepReady = item.FourteenStepReady == null ? 0 : item.FourteenStepReady;
                pB_DesignDetail.FifteenStepReady = item.TenStepReady == null ? 0 : item.FifteenStepReady;
                if (nums> pB_DesignDetail.RealNums) {
                    throw new BusException("步级设计数量不能超过总设计数量");
                }
                updateDetailList.Add(pB_DesignDetail);

            }
            await Db.UpdateAsync<PB_DesignDetail>(updateDetailList);
        }
        /// <summary>
        /// 验证清单是否有备货
        /// </summary>
        /// <param name="Id">清单id</param>
        /// <returns></returns>
        public async Task<AjaxResult> GetDesignPiakMain(string Id)
        {
          
            StringBuilder sql = new StringBuilder();
            //验证清单是否有备货  
            sql.AppendLine("  select main.* from     ");
            sql.AppendLine("PB_PickUpMain as main     ");
            sql.AppendLine("LEFT JOIN PB_DeliveryNoticeItem as item on main.ParentId = item.Id     ");
            sql.AppendLine("LEFT JOIN PB_DesignList as list on item.DesignId = list.Id     ");
            sql.AppendLine("WHERE list.Id = '"+Id+"'     ");
            List<PB_PickUpMain> pickmainlist =await Db.GetListBySqlAsync<PB_PickUpMain>(sql.ToString());
            if (pickmainlist.Count > 0)
            {
                AjaxResult res = new AjaxResult
                {
                    Success = true,
                    Msg = "该清单已有备货禁止编辑步数"
                };

                return res;
            }
            else
            {
                AjaxResult res = new AjaxResult
                {
                    Success = false,
                    Msg = "正常!"
                };
                return res;
            }
        }

       
        public async Task DesignListDelete(DesignListDelete data)
        {
            string sqlmain = string.Empty;
            if (data.SupplementaryQuantity == 0 && data.ChangeQuantity == 0) {
                sqlmain += "delete from  PB_DesignList WHERE Id='" + data.DesignId + "'; ";
                sqlmain += "delete from  PB_DesignDetail WHERE ParentId='" + data.DesignId + "';";
            } else if (data.SupplementaryQuantity>0) {
                sqlmain += $"delete from  PB_DesignDetail WHERE ParentId='" + data.DesignId + "' ORDER BY Id desc  LIMIT   "+ data.SupplementaryQuantity + "  ;";
            }
            else if (data.ChangeQuantity > 0)
            {
                sqlmain += $"delete from  PB_DesignDetail WHERE ParentId='" + data.DesignId + "' ORDER BY Id desc  LIMIT   " + data.ChangeQuantity + "  ;";
            }
            await Db.ExecuteSqlAsync(sqlmain);
            
        }

        public async Task<PB_Material> GetProductCodeData(string ProductCode)
        {
            var Data =await Db.GetIQueryable<PB_Material>().Where(m=>m.ProductCode== ProductCode).FirstOrDefaultAsync();
            return Data;
            
        }
    }
}